trying to get a oauth token using fiddler - asp.net-mvc

I've been following Scott Allen's ASP.NET MVC 5 Fundamentals on pluralsight, and can successfully request a token, using a simple HTML page, but now need to try and do this using fiddler. the reason I need to test it using fiddler, is that this is in essence the way my apu will be called. An ios device app is being written, and i have to do the api piece.
So, i enter the followdin in fiddler:
HEADER:
POST http://localhost:53140/token HTTP/1.1
Content-Type: application/json
Host: localhost:53140
Content-Length: 50
BODY:
grant_type=password:
{"userName":"something",
"password":"password"}
and I get a 400 - bad request.
i've changed the content type to : application/x-www-form-urlencoded but still a 400.
what am i doing wrong?
EDIT
Even tried "username=username&password=password" still no joy
EDIT
Whoops, had the grant_type in the wrong place. this needed to be in the body:
grant_type:password&username:username&password:password
Now i get username or password are not valid:
{"error":"invalid_grant","error_description":"The user name or
password is incorrect."}
i'll leave the post active, as this may be a red herring.

In fiddler, make sure after grant_type=password&username=username&password=password there is no space or line break.

I was troubleshooting the same error message
{"error":"invalid_grant","error_description":"The user name or password is incorrect."}
while trying this tutorial myself. It seems that the UserName being persisted onto the local database is actually the email address rather than the UserName provided in the JSON payload while invoking the /api/Account/Register Web API. You can verify this by running a T-SQL query against the [AspNetUsers] table. (If you are using LocalDb database, you can open the database located in the project’s App_Data using Show All Files.)
Please note that once the actual user name is confirmed as the email address, the email address (and possibly your password) has to be URL encoded when posting the /api/Token request.
For example:
grant_type=password&username=Alice%40yourdomain.com&password=_Password123
Hope this helps.

In fiddler you can write
Host: localhost:17271
Content-Length: 81
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
In RequestBody you can write
grant_type=password&username=Alice&password=password123&response_type=token
Hope to someone help it because my problem is solve by this type of requestbody

This is how I do it using Fiddler4 (this guide assumes you are starting from scratch):
Create a new MVC Web API 2 project in Visual Studio 2015
Ensure you set the Authentication to individual user accounts (assuming this is what you want)
Once the project has loaded build the project and start the Web Application to ensure it runs
You should get the default "ASP.NET Getting started..." page with the navigation links at the top "Home" and "API".
At this point I tend to change the "DefaultConnection" in my Web.config file to point to an actual SQL Server where I will host the ASP.NET Identity tables but you don't need to just use the localDb by default.
Fire up Fiddler4 and then click on the Composer tab on the right
Change the request type to 'POST' and then change the URL to that of your local website which you ran earlier (the VS Web API 2 project) e.g:
http://localhost:49598/api/Account/Register
Change the header text to the following:
User-Agent: Fiddler
Content-Type: application/json;charset=UTF-8
In the request body you need to compose your JSON data that will be the account you are registering for example:
{
"Email": "youremail#account.com",
"Password": "YourPassw0rd!",
"ConfirmPassword": "YourPassw0rd!"
}
With your website running hit the Execute button at the top right
If successful you should see a 200 response on the left hand side of Fiddler4 which confirms the Account Controller API action Register was called a new user was successfully registered.
Now you can test your user account by requesting an Authorization token. Clear the contents of the Request body in Fiddler4 and then change the type to POST if required.
Change the header text to the following again:
User-Agent: Fiddler
Content-Type: application/json;charset=UTF-8
In the request body paste the following (changing the values for your account obviously)
grant_type=password&username=your#account.com&password=Passw0rd!
Hit Execute again and you should see a 200 response on the left hand side of Fiddler4:
http://localhost:49598/Token
Double-click the response to open up the Inspector tab on the right hand side of Fiddler4 which should display the authorization information in JSON format (you can also see it as raw by click on the 'Raw' tab).
Look for the 'access_token=' line which will have the access token you need to make "bearer" type requests.
In layman terms this is what happens now:
a. You authenticate and get an auth token.
b. Any/All requests made to the API endpoints are done using the bearer token type and this is set in the header of your request.
c. You pass in the auth token you received and this is validated and your request is processed.
d. You should ensure your Web API 2 endpoints have the [Authorize] decoration on the methods and/or class to ensure those areas are secure.
e. If your auth token has expired (set in the App_Start\Startup.Auth.cs class 'AccessTokenExpireTimeSpan'...) then you will need to handle this for example my app calls a dumb method that requires authorization, if that fails the client side AngularJS code redirects the user to the login screen where a valid user can request another auth token by logging in.
*note: I keep the expiry times to 30 minutes for my auth tokens
Okay now to use that token in Fiddler4...
Start Fiddler4 and in the Composer tab on the right change the type to GET (Clear the contents of Request Body if you need to)
Change the header text to the following:
User-Agent: Fiddler
Host: localhost:49598
Authorization: Bearer your_very_long_auth_token_here
Change the url to the good old api/values endpoint:
http://localhost:49598/api/values
Hit the Execute button and if everything was successful you should see the 200 response on the left:
200 HTTP localhost:49598 /api/values
Double click this response and the inspector tab should open showing the JSON response
This concludes how to use Fiddler4 to test Oauth2 with Web API 2. Hope someone finds this useful if you spot any mistakes let me know in your comments and I will update this answer.

One issue I see is that it looks like you putting the username and password in the Request Body as a Json string. it should just be text with no quotes:
grant_type=password&username=UserName&password=PassWord
Then making sure you have the Content Type: application/x-www-form-urlencoded

I'm not familiar with Scott's course, but normally for OAuth2, you do a GET request to the authorization server with the credentials, which then gives you an AuthorizationCode which you then POST along with some other stuff to the token server to get your token.
I'm not aware of a shortcut where you can get a token by just passing the credentials to the token server.

Related

AWS and Cognito

I'm a newbie to this stuff so downloaded the samples which is all fine and I thought I could see what was going on and what I needed to do. However, got a bit stuck for no obvious reason so I wondered if anyone could maybe give me some hints.
I'm trying to engineer Cognito authentication and identity into an old Apache Struts 1 legacy web application written in Java, so all the activity needs to be server-side. Using the Cognito https://xxx.auth.xxx.amazoncognito.com/login? URL I can successfully authenticate and get an auth code back using this URL providing my client id, redirect URI and response_type=code so all good thus far.
If I then create an HttpClient (as per the sample code in Github) and call the token URL https://xxx.auth.xxx.amazoncognito.com/oauth2/token and write various parameters to the request body (grant_type=authorization_code, client_id=as previously, redirect_uri=my URI and code=auth code just returned), I get an "unauthorized_client" message returned. But the code is valid albeit for authorization, and the client_id is correct because I used it previously.
My log:
Cognito following successful signin, continuing to url http:[redacted]/passport/CognitoHandlerSignIn.do?code=62eeb0b1-a76b-489b-bd28-e42023a497bd
(this was the /login succeeding)
Callback from Cognito received
(following is the log dump of the /oauth2/token URI called to)
Cognito token signin URL is https:[redacted].amazoncognito.com/oauth2/token
HTTP request header, added Authorization=Basic M29wcGR0azdpYzF2YjloNGd0OTQzNXYxcmI6MW9mMmFsaWNzZGR2dHZ1NmFkOHRuc2s4cnJ0cXEyYm0yc3RqbG1mcmkyamhkdXBubG1wMw==
HTTP request header, added Content-Type=application/x-www-form-urlencoded
HTTP request body, added grant_type=authorization_code
HTTP request body, added
redirect_uri=https%3A%2F%2F<redacted>%2Fpassport%2FCognitoHandlerSignIn.do
HTTP request body, added code=62eeb0b1-a76b-489b-bd28-e42023a497bd
HTTP request body, added client_id=[redacted]
HTTP request is sun.net.www.protocol.https.DelegateHttpsURLConnection:https:
[redacted].auth.eu-west-1.amazoncognito.com/oauth2/token
HTTP Json result=<{"error":"unauthorized_client"}>
org.json.JSONException: JSONObject not found.
at org.json.JSONObject.get(JSONObject.java:454)
at
What's wrong with this picture? I tried also adding client_id, code as URL parameters but I just get an "invalid_client" message instead.
I also tried using the /oauth2/token URI directly from the Struts app to provide a token but it returns the id_token using # rather than ? in the parameter list so it is client-side only and hence can't be intercepted by the Struts app and so will be a pain to forward to the server, but I could write some Javascript to do it if I had to. It doesn't seem the path of least resistance, though, as it seems wrong that the pure Java server side call doesn't work so I must be doing something wrong which isn't obvious to me.

401 when accessing Dynamics CRM 2016 Web APIs

I am struggling to access the Dynamics 2016 CRM OData Web APIs from a console application.
We have Dynamics CRM 2016 installed, configured with Claims-based authentication, and using AD FS v3.0.
My understanding is that a console app (or web app) should be able to access the Web APIs using Windows integrated authentication (i.e. NTML or Kerberos) without any special treatment ... or maybe the OAuth flow should work when enabled.
For a regular user accessing Dynamics "pages", the authentication works fine (redirection to AD FS log in page), but accessing the OData APIs does not seem to work (for instance : https://crm.domain.org/api/discovery/v8.0/ ) :
in a browser I get a Windows login prompt and typing valid credentials always results in a HTTP 401 unauthorized error
in a brower, if I navigate to a Web API url after having logged on on the pages , then I can access the Web APIs (i.e. some cookies must be set and I am already implicitly authorized)
from code, using an HttpClient with specific valid credentials (or current credentials) , I also get a 401
Things I have tried :
if I disable Claims-based authentication completely , HttpClient works fine and I can access the OData APIs
if I leave Claims-based authentication enabled, and activate OAuth via PowerShell Add-PSSnapin Microsoft.Crm.PowerShell ; $ClaimsSettings = Get-CrmSetting -SettingType OAuthClaimsSettings; $ClaimsSettings.Enabled = $true ; Set-CrmSetting -Setting $ClaimsSettings ;.
Windows integrated authentication still does not work, but using Bearer authentication is now possible. I can use this snippet to retrieve the OAuth Endpoint for token generation, and use AuthenticationContext.AcquireTokenAsync to issue a token, and then pass it in the Authorization HTTP Header ... but then, no matter what, I get this error :
Bearer error=invalid_token, error_description
=Error during token validation!, authorization_uri=https://our.adfs.domain.org/adfs/oauth2/authorize, resource_id=https://crm.domain.org/
Am I missing something ? is that possibly a configuration issue ?
From this answer from the dynamics community forum, it looks like the api is pretty strict about the parameters and headers it requires. When doing the request, make sure you have the Cache-Control: no-cache and Content-Type: application/x-www-form-urlencoded headers set.
In the subsequent request to access the api with the retrieved token you should set the Authorization header in the form of Bearer: TOKEN (worth noting since a lot of people actually thought they could directly put the token), the OData-Version: 4.0, Cache-Control: no-cache and Accept: application/json ones too.
Looking at the different OAuth endpoints and the previously linked answer, I'm not sure the authorization uri is the right one (eg https://login.windows.net), so do you make sure that's correct. It's also stated that you should use the OAuth endpoint url and use the WWW-Authenticate header that returns the valid one, even if this route will respond with a 401. I'm sure you already saw this example, but it provides a pretty complete overview of an auth flow and how the token is retrieved using AcquireTokenAsync where you pass your resource and clientID. I might also be looking at an updated page and it's not relevant in your case.
You also want to check if the resource id you specified is the correct one, some people reported to have to specify one in the form of https://crm3.domain.org/ or https://crm4.domain.org/ instead of the bare one, so that could be one thing.
It could also be a configuration issue, given what #l said about the fact an IP would work instead of the domain name. It could very well be a certificate problem, where it's not validated correctly or untrusted, thus creating the error you see even if it's not the appropriate message. Also make sure your 443 port is allowed through your firewall(s).
One interesting post where the author explains that the Form Authentication setting of the AD FS Management Console was required for him to proceed (it's CRM 2013, but might still be related).

Modified OAuth tokens can still authenticate / authorize successfully

Using Owin and OAuth, I've noticed that if you modify the last character of a token you can still get authenticated / authorized successfully.
I'm using a C# WebAPI application, but I don't know if this applies to OAuth in general. This might be by design but it seems like strange behaviour to me so I'm curious to know why this happens.
To replicate this behaviour:
In Visual Studio, create a new project and select 'ASP.NET Web Application' as the template.
Choose the 'Web API' template, and choose 'Individual User Accounts' as the authentication type.
Build the project.
Using a REST client, POST to http://localhost:23220/api/account/register * with a Content-Type: application/json header and the following body:
{
"UserName": "test",
"Password": "password",
"ConfirmPassword": "password"
}
Using a REST client, POST to http://localhost:23220/token * with no headers and the following body:
grant_type=password&username=test&password=password
Using a REST client, GET http://localhost:23220/api/values * with a Authorization: Bearer xxx header, where xxx is the access token you generated in the previous request. This request should be authorized and you should get a 200 response.
Make the same GET request again, but this time modify the last character of the Authorization header value by incrementing it by 1. So for example, if the last character is a, change it to b; if it's 1, change it to 2 etc. The request will still be successful.
* Change the port accordingly.
AccessTokenFormat - The data format used to protect the information contained in the
access token. If not provided by the application the default data
protection provider depends on the host server. The SystemWeb host on
IIS will use ASP.NET machine key data protection, and HttpListener and
other self-hosted servers will use DPAPI data protection.
Since setting up the project this way will run under IIS Express, the token is protected with the MachineKey API. I was not able to find a description of the exact data format of the encrypted value, but from previous work in cryptography, I expect perhaps there is padding at the end. This padding would not be protected by the token's signature, but this doesn't matter as it is just stripped off and discarded. Note that the range of changes is limited, so I expect only the last few bits of the last byte can be modified.

Passing DataSnap Authentication Credentials with jquery and AJAX

I am attempting to build a Delphi XE2 DataSnap Rest server to be used as a 3rd party API for access to our DBMS.
I have extended the functionality of the sample methods provided when using the rest datasnap wizard in xe2 with authentication and authorization.
I can confirm that all the server methods I have written do pass back the data expected when accessed directly through the browser.
The issue comes from trying to authenticate to the server from a $.ajax() call.
When accessed from the browser address bar, you are prompted for the username and password and, when you enter "dev" for both, allows you to continue.
When setting the ajax() username and password params to "dev", I am getting a HTTP 401 response.
I think I am doing it correctly, but here is the code snippet:
$("#contentdiv").click(function(){
$.ajax({
type:"GET",
cache:"false",
username:"dev",
password:"dev",
url:"http://192.168.0.2:8080/datasnap/rest/TServerMethods1/methodname/",
dataType:"jsonp",
statusCode: {
200: function(data){
alert('success ');
}
}
});
});
If I turn off authentication, I can successfully get a HTTP 200 response (albeit with a syntax error in the JSON Delphi DataSnap is returning, but that is a question for a different time).
Also, what is worth know - if I log in manually and then run the ajax, it works - I am assuming that this is because the credentials are cached or some such.
Quite new to both these technologies, so be gentle.
If I've left something out that could be of import, let me know and I will get it up here.
Your Ajax code uses JSONP, the server uses basic authentification.
A comment on this answer says that JSONP cannot contain the USER / PWD headers which Basic Auth requires:
Basic Authentication with jQuery.ajax request and jsonp
The reason is (quote from the answer above):
JSONP works differently, it's a GET request via a tag include
to get the file, so you're not sending special headers or anything.

No browser is sending Authorization info in header

I'm looking at this and this and it would appear 'easy' to send the credentials in the URL. For example:
http://gooduser:secretpassword#www.example.com/webcallback?foo=bar
This is all well and good but it doesnt work. I've turned fiddler on and for Chrome the Authorization header isnt sent. It appears to exhibit the same behaviour for other browsers (i've got a breakpoint on the server and no Authorize header turns up for Firefox,Safari or IE either)
How to make it better?
Stumbled across this while researching various basic auth implementations.
Browsers generally only send basic auth if they receive a 401 challenge response from the server (more on basic auth protocol). If the endpoint in question accepts both authenticated and non-authenticated users, then a browser-based request will likely never be prompted for the auth parameters.
The easiest way to test this type of setup is to send a curl request (which sends the authentication parameters regardless) to your server endpoint and validate receipt of the authorization header:
curl 'http://gooduser:secretpassword#www.example.com/webcallback?foo=bar'
OK so after much searching and experimenting the approach
http://gooduser:secretpassword#www.example.com/webcallback?foo=bar
does work.
However one needs to be careful to ensure that the secret password DOES NOT contain any special characters. Use a password containing only letters and numbers and a hypen(if you must) and it should work.

Resources