Set HTTP requests defaults in IntelliJ HTTP request client editor - intellij-idea

In IntelliJ http request editor; is there a way to set the common config for all the requests in the file (and globally) ?
For example I would like to specify an authorization header for all the requests.
Current code
GET http://localhost:8080/api/foo
Authorization: Bearer my-token
The code I am trying to achieve:
Desirable code
<common headers>
Authorization: Bearer my-token
GET http://localhost:8080/api/foo
GET http://localhost:8080/api/bar
GET http://localhost:8080/api/baz

It's a bit late but i will try to give an answer in case someone is coming around.
I'm not sure it is exactly what you are looking for but maybe it help.
If you are getting your token dynamically from a login endpoint, you can store the token in a variable and use it later in any request.
Exemple:
### Login
POST http://localhost:8080/login
Content-Type: application/json
{
"email": "someEmail",
"password": "somePassword"
}
> {%
client.global.set("auth_token", response.headers.valuesOf('x-auth-token')[0]);
%}
### Get user
GET http://localhost:8080/user/someUserId
Authorization: Bearer {{auth_token}}
In this case, i store my token coming from the header x-auth-token in a variable auth_token. Than i use it in the authorization header for all my next requests.
Found from the official JetBrains website HTTP response handling exemples
Have a nice day!

Related

Setting variables from the response in IntelliJ IDEA's HTTP request generator

I am enjoying IntelliJ IDEA's HTTP request generator as an alternative to Postman etc.
Currently, my application uses an ephemeral key for JWTs. You know what kind of pain it is... Every time you restart the application you MUST authenticate again, even if the old token is still (temporally) valid.
Currently I have to run my OAuth authentication request with my credentials, copy-and-paste the JWT from the output JSON, and then paste in into next request's Authorization header
GET http://localhost:8080/api/auth/v1/token
Authorization: CCB [... static token...]
{
"id_token": "eyJhbGciOiJIUzI1NiJ9....", <== copy that!
"refresh_token": "eyJhbGciOiJIUzI1NiJ9....",
"expires_in": 1634292409144,
"user_details": {
And
PATCH http://localhost:8080/api/v1/example/runImportJob
Authorization: Bearer <== paste!
Question
I know that IntelliJ IDEA supports {{variables}}. I'd like to ask if it is possible to set the output of the token invocation into a variable which I'll then reference in the Authorization header
Desiderata
PATCH http://localhost:8080/api/v1/example/runImportJob
Authorization: Authorization {{jwt}}
And to run the authentication request (GET .../token) which ultimately sets the jwt variable, after jsonpath-ing the response of corse
You can try using client.global.set and client.global.get to save/load variables. See the example at https://www.jetbrains.com/help/idea/http-response-handling-examples.html#script-var-example .

axios api authentication headers jwt and security

Two questions here:
I was not able to pass in a post request using axios and authorization headers as such:
axios.post('http://localhost/dashboard', {headers: { 'Authorization': 'JWT xxxxxx' }})
But I was able to get it to work with a preset: axios.defaults.headers.common['Authorization'] = 'JWT xxx'
Am I missing something as to why the headers parameter was sending the "headers" as a data payload instead of as an actual header?
Once I generate a JWT from my login page, on each page request after that I am only showing the page if the response.status is 200. Is this the correct way to redirect someone back to a login page if their jwt is fake or invalid for accessing the page?
The flow is:
/login for user to get JWT
immediately directed to /dashboard but before they are an api call is made to /dashboard using the JWT and if status code is 200, then the /dashboard page is shown. Is this correct or should I be implementing something more than just a 200 code?
Am I missing something as to why the headers parameter was sending the "headers" as a data payload instead of as an actual header?
Because you're passing the headers as the data payload. I suggest reading the axios docs for axios.post()
It's common to automatically refresh the JWT instead of logging the user out. Depends on your security requirements. For ex., if you were a bank, it's better to log the user out than to auto refresh the JWT.
Instead of checking for 200, check if the status is 403 (or whatever status your backend returns for an invalid JWT). If your backend errors (500), or receives a bad request (400), it's not relevant to an invalid JWT and you'd be logging the user out for nothing.

Issue of invalid access token when trying to get households

I haven't had an issue getting access tokens, but when I try to test my access token by requesting households, I am getting 'Invalid Access Token' as a response. My refresh token appears to be working fine, but even refreshed access tokens are failing for this request.
I may be setting up my curl incorrectly for this request, can you please let me know exactly which tokens/keys/values are to be placed in these 2 headers, I don't find the documentation to be clear:
Authorization: ***** Hidden credentials *****
X-Sonos-Api-Key: 00000000-0000-0000-0000-000000000000
Thanks
In the sample getHouseholds request, you need to provide your access token as a header in the format:
Authorization: Bearer <Access-Token>
and then your API Key (generated when you created your integration) in a second header:
X-Sonos-Api-Key: <Api-Key>
Be sure to also include the content-type header:
Content-Type: application/json

Resumable upload returns Unauthorized when uploading chunk

Today I have a problem with the resumable upload feature of OneDrive via the Microsoft Graph API, as described here. I have integration tests which previously worked, which now fail.
I successfully call createUploadSession and get an uploadUrl to use. I've replaced actual tokens with "XXX" here.
POST https://graph.microsoft.com/V1.0/groups/273c2c33-8533-445d-ae65-4b63be296995/drive/root:/c2fa1a83-74f3-444b-9263-c9539ee3eae2.txt:/createUploadSession HTTP/1.1
Authorization: Bearer XXX
{
"item": {
"#microsoft.graph.conflictBehaviour": "replace"
}
}
Response:
{
"#odata.context": "https://graph.microsoft.com/V1.0/$metadata#microsoft.graph.uploadSession",
"expirationDateTime": "2017-04-27T11:07:50.5650598Z",
"nextExpectedRanges": ["0-"],
"uploadUrl": "https://sageglodbizp.sharepoint.com/sites/SharePointTests/_api/v2.0/drive/items/01LQXPMG56Y2GOVW7725BZO354PWSELRRZ/uploadSession?guid='9d14ed72-e532-442e-94e8-70952b365527'&path='~tmp0B_c2fa1a83-74f3-444b-9263-c9539ee3eae2.txt'&overwrite=True&rename=False&access_token=XXX"
}
So the uploadUrl is there. Then, I try to PUT a chunk to this url but get a 401 Unauthorized in response:
PUT https://sageglodbizp.sharepoint.com/sites/SharePointTests/_api/v2.0/drive/items/01LQXPMG56Y2GOVW7725BZO354PWSELRRZ/uploadSession?guid='9d14ed72-e532-442e-94e8-70952b365527'&path='~tmp0B_c2fa1a83-74f3-444b-9263-c9539ee3eae2.txt'&overwrite=True&rename=False&access_token=XXX HTTP/1.1
Authorization: Bearer XXX
Response
HTTP/1.1 401 Unauthorized
As I'm using the URL provided by the Graph API, I believe this to be a bug. I'm passing the same bearer token to the second call as the first (I've also tried it with no access token, given that one is in the URL).
I have tried this with two different Office 365 tenants, both with the same result.
This has previously worked. Any thoughts on why this has stopped working? Is it correct that the uploadUrl points to my SharePoint endpoint rather than the Graph API?
I should also add, a non-resumable upload directly to the Graph API works fine.
Any suggestions most welcome.
EDIT:
This seems to be affected by the length of the filename to which you upload:
myfile-123100000000000000000000000.txt works successfully
myfile-1231000000000000000000000000.txt fails
This was confirmed as a bug by Microsoft and fixed on Saturday 29 / Sunday 30 April 2017.
Per the documentation:
Including the Authorization header when issuing the PUT call may result in a HTTP 401 Unauthoized response. The Authoization header and bearer token should only be sent when issueing the POST during the first step. It should be not be included when issueing the PUT.
If you remove the Authorization: Bearer XXX header from your PUT call should resolve this issue.

Sending JWT token in the headers with Postman

I'm testing an implementation of JWT Token based security based off the following article. I have successfully received a token from the test server. I can't figure out how to have the Chrome POSTMAN REST Client program send the token in the header.
My questions are as follows:
1) Am I using the right header name and/or POSTMAN interface?
2) Do I need to base 64 encode the token? I thought I could just send the token back.
For the request Header name just use Authorization.
Place Bearer before the Token. I just tried it out and it works for me.
Authorization: Bearer TOKEN_STRING
Each part of the JWT is a base64url encoded value.
Here is an image if it helps :)
Update:
The postman team added "Bearer token" to the "authorization tab":
I am adding to this question a little interesting tip that may help you guys testing JWT Apis.
Its is very simple actually.
When you log in, in your Api (login endpoint), you will immediately receive your token, and as #mick-cullen said you will have to use the JWT on your header as:
Authorization: Bearer TOKEN_STRING
Now if you like to automate or just make your life easier, your tests you can save the token as a global that you can call on all other endpoints as:
Authorization: Bearer {{jwt_token}}
On Postman:
Then make a Global variable in postman as jwt_token = TOKEN_STRING.
On your login endpoint:
To make it useful, add on the beginning of the Tests Tab add:
var data = JSON.parse(responseBody);
postman.clearGlobalVariable("jwt_token");
postman.setGlobalVariable("jwt_token", data.jwt_token);
I am guessing that your api is returning the token as a json on the response as:
{"jwt_token":"TOKEN_STRING"}, there may be some sort of variation.
On the first line you add the response to the data varibale.
Clean your Global
And assign the value.
So now you have your token on the global variable, what makes easy to use Authorization: Bearer {{jwt_token}} on all your endpoints.
Hope this tip helps.
EDIT
Something to read
About tests on Postman: testing examples
Command Line: Newman
CI: integrating with Jenkins
Nice blog post: master api test automation
Here is how to set token this automatically
On your login/auth request
Then for authenticated page
I had the same issue in Flask and after trying the first 2 solutions which are the same (Authorization: Bearer <token>), and getting this:
{
"description": "Unsupported authorization type",
"error": "Invalid JWT header",
"status_code": 401
}
I managed to finally solve it by using:
Authorization: jwt <token>
Thought it might save some time to people who encounter the same thing.
If you wish to use postman the right way is to use the headers as such
key: Authorization
value: jwt {token}
as simple as that.
Open postman.
go to "header" field.
there one can see "key value" blanks.
in key type "Authorization".
in value type "Bearer(space)your_access_token_value".
Done!
For people who are using wordpress plugin Advanced Access Manager to open up the JWT Authentication.
The Header field should put Authentication instead of Authorization
AAM mentioned it inside their documentation,
Note! AAM does not use standard Authorization header as it is skipped
by most Apache servers. ...
Hope it helps someone! Thanks for other answers helped me alot too!!
Everything else ie. Params, Authorization, Body, Pre-request Script, Tests is empty, just open the Headers tab and add as shown in image. Its the same for GET request as well.
I did as how moplin mentioned .But in my case service send the JWT in response headers ,as a value under the key "Authorization".
Authorization →Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJpbWFsIiwiZXhwIjoxNDk4OTIwOTEyfQ.dYEbf4x5TGr_kTtwywKPI2S-xYhsp5RIIBdOa_wl9soqaFkUUKfy73kaMAv_c-6cxTAqBwtskOfr-Gm3QI0gpQ
What I did was ,make a Global variable in postman as
key->jwt
value->blahblah
in login request->Tests Tab, add
postman.clearGlobalVariable("jwt");
postman.setGlobalVariable("jwt", postman.getResponseHeader("Authorization"));
in other requests select the Headers tab and give
key->Authorization
value->{{jwt}}
Somehow postman didn't work for me.
I had to use a chrome extension called RESTED which did work.
In Postman latest version(7++) may be there is no Bearer field in Authorization
So go to Header tab
select key as Authorization and in value write JWT
x-access-token on headers works for me.
key: x-access-token
value: token