How to develop test-automation using Postman when OAuth 2.0 authorization is required - asp.net-web-api

I have an ASP.NET Web API 2 which is using OAuth 2.0 for authorization. And let's imagine I have a simple Web API method, like:
GET: http://host/api/profiles/user123 (requires OAuth 2.0 token)
So, with Postman, it is easy to test this Web API. I get an OAuth token for user123 from the Web API OAuthAuthorization method and then I use that token in the header of the HTTP request:
GET /api/profiles/user123 HTTP/1.1
Host: {host}
Authorization: Bearer {Token}
Content-Type: application/json
Cache-Control: no-cache
However, if I save my test and run it later (either by Postman itself or by Newman), the token will be expired at that time and it won't work.
How can I make Newman to get a new token automatically for user123 and use it in the HTTP request?
Note: I know how to use Postman's Authentication helpers to ask for a new token. But this scenario doesn't fit the test-automation. In test-automation, I want to remove any human interaction.

It's simple, get your access token at run time and save it into environment variable. Then use it in your next Get request.
In Get Token request, do this in Tests sections:
var body = JSON.parse(responseBody);
pm.environment.set('AccessToken', body.access_token);
In your main Get request, you can use the environment variable in Authorization header:
Authorization: Bearer {{AccessToken}}
Hope this helps.

Related

Laravel Sanctum CSRF Token Mismatch using Thunder Cilent (Testing API)

CSRF Token Mismatch when using Thunder Cilent to test Laravel Sanctum API. Works fine on app, just not when testing API outside app.
Trying to test API with Laravel Sanctum with Thunder Cilent (Think Postman but VSCode extension). However, despite setting the xsrf-token and Cookie, I'm always getting CSRF token mismatch.
Note logging on works fine in the app, it's only the api testing with thundercilent that's failing.
Getting the CSRF Token
GET http://localhost:8000/sanctum/csrf-cookie
Response Cookies
xsrf-token: eyJpdiI6ImN6Q3JLVEQrYnhXVXhyVWFQWC9YQlE9PSIsInZhbHVlIjoia2F2aTNjNDU2cTZURHRSSTN5Ny9ETnFJMGZoN0I2dmZ3bTA0UEZ6UjhzdCtCRjRPam9OSW5TWVkzYzAvMTQ0ZEp6b2JvYVdhRWg2TGsrejlkcnYzTGY3eGNFcTRGN253dUUxZjE3YXJBSFlVUHk4aGM5RmVYRWF6UFY2ZGRnYUEiLCJtYWMiOiI4OWU3OGI3MzQ3ZTdiNTNiZDQ2Yjg0ZDE3YWNiYmVhNDQ1NTI0MmI3MTY1NjdlZGI5ZGJlZDJlN2Q5NTc0ZjRhIiwidGFnIjoiIn0%3D
laravel_session: eyJpdiI6IjV6VTV4di9IMXNST1ZvNVh0K1pZelE9PSIsInZhbHVlIjoiTSsycEVWdjJ1VTc4dU81TVNJWTJ4aTRHOE81WTVHVW1OeU55OEt3cVU3bHc5N090dEdPQy9yZGJsamhOaDUzaFZmZVp0Z2FTeGp4UWJyVFVmSDdnVytTNS9SZTF5c0daak9EZ1I1V0w3aWpjTnVESWtIRmR2QzNGZ1VqWlZHZ2oiLCJtYWMiOiI0Mzg4NGI4MTc5MGQ1MDE1NTUxY2VmNGRmNGFkNjUyYmI1MjUwMTJiODQ4NmY4M2E5OTRlZGRlNTM3NjAzNTg1IiwidGFnIjoiIn0%3D
Logging in
POST http://localhost:8000/login
Body: {
"email": "example#example.com",
"password": "password"
}
Raw Headers:
User-Agent: Thunder Client (https://www.thunderclient.com)
Accept: application/json
Referer: http://localhost:3000
xsrf-token: eyJpdiI6ImN6Q3JLVEQrYnhXVXhyVWFQWC9YQlE9PSIsInZhbHVlIjoia2F2aTNjNDU2cTZURHRSSTN5Ny9ETnFJMGZoN0I2dmZ3bTA0UEZ6UjhzdCtCRjRPam9OSW5TWVkzYzAvMTQ0ZEp6b2JvYVdhRWg2TGsrejlkcnYzTGY3eGNFcTRGN253dUUxZjE3YXJBSFlVUHk4aGM5RmVYRWF6UFY2ZGRnYUEiLCJtYWMiOiI4OWU3OGI3MzQ3ZTdiNTNiZDQ2Yjg0ZDE3YWNiYmVhNDQ1NTI0MmI3MTY1NjdlZGI5ZGJlZDJlN2Q5NTc0ZjRhIiwidGFnIjoiIn0%3D
Cookie: XSRF-TOKEN=eyJpdiI6ImN6Q3JLVEQrYnhXVXhyVWFQWC9YQlE9PSIsInZhbHVlIjoia2F2aTNjNDU2cTZURHRSSTN5Ny9ETnFJMGZoN0I2dmZ3bTA0UEZ6UjhzdCtCRjRPam9OSW5TWVkzYzAvMTQ0ZEp6b2JvYVdhRWg2TGsrejlkcnYzTGY3eGNFcTRGN253dUUxZjE3YXJBSFlVUHk4aGM5RmVYRWF6UFY2ZGRnYUEiLCJtYWMiOiI4OWU3OGI3MzQ3ZTdiNTNiZDQ2Yjg0ZDE3YWNiYmVhNDQ1NTI0MmI3MTY1NjdlZGI5ZGJlZDJlN2Q5NTc0ZjRhIiwidGFnIjoiIn0;laravel_session=eyJpdiI6IjV6VTV4di9IMXNST1ZvNVh0K1pZelE9PSIsInZhbHVlIjoiTSsycEVWdjJ1VTc4dU81TVNJWTJ4aTRHOE81WTVHVW1OeU55OEt3cVU3bHc5N090dEdPQy9yZGJsamhOaDUzaFZmZVp0Z2FTeGp4UWJyVFVmSDdnVytTNS9SZTF5c0daak9EZ1I1V0w3aWpjTnVESWtIRmR2QzNGZ1VqWlZHZ2oiLCJtYWMiOiI0Mzg4NGI4MTc5MGQ1MDE1NTUxY2VmNGRmNGFkNjUyYmI1MjUwMTJiODQ4NmY4M2E5OTRlZGRlNTM3NjAzNTg1IiwidGFnIjoiIn0%3D;
I copied how this SO Postman example, but it's not working at all. Thunder Cilent doesn't have pre-run scripts so I can't add cookies that way.
Open thunder client, switch to Env and create an environment.
Click on the options button of your collection and choose settings.
Add a test to your collection by navigating to the Tests tab, then select Set Env Variable, set query to cookie.xsrf-token and value to {{XSRF-TOKEN}}
In the Headers tab, add an header named X-XSRF-TOKEN with value {{XSRF-TOKEN | urlDecode}}.
Create a request to /sanctum/csrf-cookie to refresh CSRF Token if it expires
This should fix CSRF Token.
Consult docs for more information: https://github.com/rangav/thunder-client-support
Decided just to use token based auth for API testing instead. Much easier then messing around with CSRF cookies.
Notes for my future self.
When testing the Token based auth, you need to set the accept to application/json otherwise it won't work.
If using collections, don't delete the Accept header in the request, just untick the box. Otherwise the request would override the collection header with something else and not work.

How to send POST request to secure Laravel API route from Postman

I am having problems in submitting POST request to secured Laravel API routes via Postman. My GET requests work fine, but my POST cant go through the security even though I have provided an api token.
So my question is: How properly to send POST request to secured Laravel API routes from Postman?
Add this is the request header.
[enter image description here][1]accept: application/json
content-type: application/json
authorization: "your_token"
Found the solution:
Set your Authorization to API Key:
Next, in headers section you need to add X-Requested-With field:

How to get an access token from Google without an api library?

I am working on an Elixir Phoenix web project where I want to interact with Google's Indexing API.
Google uses OAuth2 to authenticate api requests and actually has a decent documentation on this.
But it only explains the process using one of the supported libraries in Python, Java, PHP or JS.
I would like to make the HTTP requests by myself to retrieve that access token. But the request format (including headers or parameters) is nowhere documented and I cannot even figure out from the libraries' source code.
I have tried requesting https://accounts.google.com/o/oauth2/token (also other eligible URLs) in Postman with the "OAuth 2.0" request type.
But it was all just guessing and trying. All the research did not help.
There are useful instructions including HTTP/Rest examples at Using OAuth 2.0 for Web Server Applications. Each step has the individual parameters fully documented. Here are some useful excerpts.
Send user to Google's OAuth 2.0 server. Example URL:
https://accounts.google.com/o/oauth2/v2/auth?
scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.metadata.readonly&
access_type=offline&
include_granted_scopes=true&
state=state_parameter_passthrough_value&
redirect_uri=http%3A%2F%2Foauth2.example.com%2Fcallback&
response_type=code&
client_id=client_id
Retreive authorization code (your domain). Example:
https://oauth2.example.com/auth?code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7
Request access token. Example:
POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded
code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&
client_id=your_client_id&
client_secret=your_client_secret&
redirect_uri=https://oauth2.example.com/code&
grant_type=authorization_code
Use API. Example:
GET /drive/v2/files HTTP/1.1
Authorization: Bearer <access_token>
Host: www.googleapis.com/

Spring security OAuth2 request as object instead of query parameters

I want to customise OAuth Endpoint URI's.
I want to sent parameters in post body instead of query params.
now my request is like -
example.com/oauth/token?grant_type=password&client_id={CLIENT_ID}&client_secret={CLIENT_SECRET}&username={USERNAME}&password={PASSWORD}
But I want it like this.
example.com/oauth/token
Request body -
{
grant_type=password,
client_id={CLIENT_ID},
client_secret={CLIENT_SECRET},
username={USERNAME},
password={PASSWORD}
}
How should I do it?
The token endpoint of a properly-implemented authorization server does NOT accept GET requests because RFC 6749, "3.2. Token Endpoint" says as follows:
The client MUST use the HTTP "POST" method when making access token requests.
So, your authorization server's token endpoint should reject GET requests.
RFC 6749, "4.3. Resource Owner Password Credentials Grant" says that request parameters of a token request using Resource Owner Password Credentials flow should be embedded in the request body in the format of "application/x-www-form-urlencoded". The following is an excerpt from "4.3.2. Access Token Request".
POST /token HTTP/1.1
Host: server.example.com
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded
grant_type=password&username=johndoe&password=A3ddj3w
Therefore, you don't have to customize your authorization server. If the server is implemented correctly, its token endpoint accepts POST requests.
The token endpoint created by spring-oauth2 already deals with POST as well.
It would be hard to customize it to accept a JSON request body, because the TokenEndpoint class expects all the params as #RequestParam params.
However, if your concern is about security (as HTTPs does not secure query parameters) you indeed can send the request parameters through post. It is just a matter of sending the request in the form "form-data" or "x-www-form-urlencoded". These are 2 ways of sending arbitrary key-value parameters in the request body, in a way that appears to the server as they are regular request parameters. So it is a matter of making your client using this.
Also, note that in spring-oauth2 it is possible to disable the GET endpoint, this way forcing your clients to use POST with one of the ways above.

Token based authentication for user and separate module

I have 2 scenarios where I want to implement the token based authentication:
I want to implement token based authentication when a user logs in. i.e.. based on username and password , user should get a token and that token should be used with every request.
I have a separate independent module which has ID and secret Key. It has to communicate with server in specific interval. I want to implement token based authentication for this module also.
In both the cases token should have these properties:
It should be in payload.
It should have a timeout period
When token expires server should provide a new token,if the session is not expired else it should logout.
Is OAuth 2.0 right choice? If any other approach is better, Please tell me.
What should I do to solve this problem?
Which is the best place to put token in request -Payload or header? and Why?
OAuth 2.0 is a good choice for the requirements you mentioned: timeout period and refresh-ability.
Stormpath has an excellent OAuth2.0 implementation that gives you what you are looking for out of the box.
Stormpath has both remote and local OAuth2 Implementations and both are freely available. For the remote case you can rely on our backend using any REST client (http://docs.stormpath.com/guides/token-management/) and any of our SDKs. For the local case you can use our Servlet plugin to run a Web-app with out of the box OAuth2 support. Using the docs link above, you can find documentation for these resources.
Using the Stormpath Spring Boot integration, for instance, you could do something like this:
http -v --form POST http://localhost:8080/oauth/token \
> 'Origin:http://localhost:8080' \
> grant_type=password username=micah+demo.jsmith#stormpath.com password=<actual password>
(This example uses httpie to interact with a locally running Spring Boot instance). The line I've bolded above conforms to the OAuth2.0 spec for authenticating with usernames and passwords. What you get back is a response like:
HTTP/1.1 200 OK
Cache-Control: no-store
Content-Length: 325
Content-Type: application/json;charset=UTF-8
Date: Tue, 04 Aug 2015 16:02:08 GMT
Pragma: no-cache
Server: Apache-Coyote/1.1
Set-Cookie: account=eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxNDQyNmQxMy1mNThiLTRhNDEtYmVkZS0wYjM0M2ZjZDFhYzAiLCJpYXQiOjE0Mzg3MDQxMjgsInN1YiI6Imh0dHBzOi8vYXBpLnN0b3JtcGF0aC5jb20vdjEvYWNjb3VudHMvNW9NNFdJM1A0eEl3cDRXaURiUmo4MCIsImV4cCI6MTQzODk2MzMyOH0.wcXrS5yGtUoewAKqoqL5JhIQ109s1FMNopL_50HR_t4; Expires=Wed, 05-Aug-2015 16:02:08 GMT; Path=/; HttpOnly
{
"access_token": "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxNDQyNmQxMy1mNThiLTRhNDEtYmVkZS0wYjM0M2ZjZDFhYzAiLCJpYXQiOjE0Mzg3MDQxMjgsInN1YiI6Imh0dHBzOi8vYXBpLnN0b3JtcGF0aC5jb20vdjEvYWNjb3VudHMvNW9NNFdJM1A0eEl3cDRXaURiUmo4MCIsImV4cCI6MTQzODk2MzMyOH0.wcXrS5yGtUoewAKqoqL5JhIQ109s1FMNopL_50HR_t4",
"expires_in": 259200,
"token_type": "Bearer"
}
This provides a bearer token that can be used on subsequent requests as well as an expiration. Plus, it has the advantage of being a JWT - JSON Web Token. The JWT is cryptographically signed to ensure that it hasn't been tampered with and it can be decoded to provide additional meta-information to your client, including user information, access controls and expiration.
You could do something very similar using the grant_type=authorization_code for interacting using an id and secret, such as for the independent module you mentioned.
This article goes into more detail on token authentication with Java.
Full disclosure: I am a Stormpath employee and I wrote the article referenced above.

Resources