Axios impossible to read 403 answer body - vue.js

I am trying to use Vue + axios to query the N26 bank API. To do so you need to ask for a MFA token and go through MFA authorization. The first step is to get the MFA token, by querying https://api.tech26.global/oauth2/token/ and they reply with a 403 with the token in the data. It works when I curl :
% curl -i -H "Authorization: Basic bmF0aXZld2ViOg==" -H "Content-type: application/x-www-form-urlencoded" -H "device-token: aDeviceToken" https://api.tech26.global/oauth2/token --data "username=myUsername&password=MyPassword&grant_type=password"
HTTP/1.1 403 Forbidden
{"userMessage":{"title":"A second authentication factor is required.","detail":"Please provide your second form of authentication."},"mfaToken":"mfaToken","error_description":"MFA token is required","detail":"MFA token is required","hostUrl":"https://api.tech26.global","type":"mfa_required","error":"mfa_required","title":"A second authentication factor is required.","message":"Please provide your second form of authentication.","userId":"MyUserID","status":403}
As you can see, the MFA token is in the answer and can be used to continue the workflow.
However when doing so with Axios on Vue.js, It is impossible for me the get the message with the 403 reply:
let data = new URLSearchParams();
data.append('grant_type', 'password');
data.append('username', 'myUserName');
data.append('password', 'MyPassword');
let headers = { "Authorization": "Basic bmF0aXZld2ViOg==", "Content-type": "application/x-www-form-urlencoded", "device-token": "MyDeviceToken" };
let response = await axios.post(`https://api.tech26.global/oauth2/token`, data, { headers });
console.log(response)
But the only thing in the logs is "XHR OPTIONS https://api.tech26.global/oauth2/token", and when I click on it it just shows 403, without the response body. I tried looking for a way to retrieve the 403 body message, but nobody seems to be interested in this (and it is quite weird that they reply with 403 when this is the normal workflow). Does anyone know how to fetch the response body with axios please ?

This is actually a CORS problem.
The OPTIONS message is the preflight request the browser automatically sends (because you have a custom header: device-token) before it can proceed with the POST. Since the preflight failed with 403, the POST request is not actually sent to the server.
You'll need another way to get the mfaToken, and that's beyond the scope of the question.

Related

HTTP GET Jwt Request work with postman but same with axios return 401 Unauthorized

I have a request against an enpoint that need a token
With postman request work fine and answere 200 and looks like that:
Axios has previously done a succesfull login request that gave it to have a valid token
In the login callback methode I allowed axios to produce request with a valid jwt token:
axios.defaults.headers.common['Authorization'] = token
Then axios do a call is done by this line:
axios.get("https://localhost:44336/api/CurrentBet")
But it produces 2 requests: one with answer 204 No Content and another one with answer 401 Unauthorized
the first request is:
the second request is :
Do you have any idea about what happens and how to resolve it?
For jwt , axios should be set with code bellow;
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;

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

Set HTTP requests defaults in IntelliJ HTTP request client editor

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!

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.