400 Bad Request if Authorization Bearer token used - angularjs

I'm using PostMan to troubleshoot an odd 400 error with my Angular / NodeJS app.
I'm trying to GET https://example.com/login.html and the request has two headers:
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGc...== and Accept: text/html
This returns a 400 Bad Request error (server: cloudflare-nginx)
This works fine (returns 200) if:
I access the file in my local environment on http://localhost:5000/login.html (no https factor?) -or-
I remove Authorization: Bearer from the header
If I watch my NodeJS server logs, I don't even see the request come through. So /login.html doesn't even get hit, I assume because Express is rejecting it before my app.use(logger('dev')); picks it up.
UPDATE: I believe Cloudflare is kicking it back with 400 prior to the request ever reaching Heroku.
A few more points:
I am using JWT to authenticate users, which is where the Bearer token comes from.
If I access other endpoints, such as /profile with the Bearer token, it responds properly with the user profile from decoding the token.
My question is:
Why would this request be a "Bad Request" when it works on other endpoints?
Is there a way to catch this and do something with the request before it's returned as 400?

As it turns out, the issue was related to my implementation of JWT. For some reason, one user continued to receive a token that caused these 400 errors, even though the token was verified as valid using JWT.io.
I made two significant changes that fixed the issue:
I was embedding the full user profile (long JSON) in the token payload. I reduced it to just their userid, both for performance reasons (far smaller size) and just in case something in the complex payload was causing the issue.
I switched from JWT-Simple to jsonwebtoken in my node implementation.
I'm just glad that worked. My next step was to switch from 'Authorization' to 'x-encoded-auth' or some other custom name.

#James, I don't have enough reputation to post a comment on your answer, but I thought it would be helpful to others struggling with this issue to state that your suggestion to reduce the complexity/size of the signed user indeed resulted in resolving similar issues I was experiencing. This was on my list of performance optimizations anyway - but it didn't occur to me that it could be a cause for error in this scenario - so you deserve the credit... thanks!
For readers - there are some useful links in this SO thread about max size for tokens: What is the maximum size of JWT token?
And this is a tool I use to check the validity of a generated tokens... https://www.base64decode.org/
Hope this justifies the upgrade from comment to answer!

Related

IdentityServer API unauthorized if hosted in IIS

I added additional API to the Duende IdentityServer 6.2 as described here. Then I tried to access it from a sample App, using typed httpClient using their own library called AccessTokenManagement (aka Identity.Model) pretty much following their simple example. I use Authorization Code flow, everything pretty much simple and default.
It works well until both server and client are on the same dev machine under localhost. As soon as I publish IdentityServer to IIS, the API stops to work, while the rest still works well (I can be authenticated, and I see in the Fiddler that token exchanges work normally).
The call to API consists from two calls:
Calling to /connect/token using refresh token. Server returns access token.
Calling my endpoint using this new access token.
The flow fails on the step 1. Call to /connect/token is already unauthorized and I can't understand why. The "good" and "bad" calls looks the same, I cannot see any differences. Previous call moment ago to /connect/userinfo consists of the same two steps and it works. Logs on both server and client give no clues.
No reverse proxies, just good plain simple URI. Automatic key management is enabled and the keys are in the SQL table, common for dev and published server. Asp.Net Core Data Protection is enabled and keys are also common.
Relevant parts of logs are below. I noticed that "No endpoint entry found for request path" is specific to IdentityServer and it doesn't actually mean that endpoint was not found. It was found but not processed. I also noticed reacher response headers from bad request and log entry about "Cookie signed-in" in good request but not sure what does it mean and whether it's relevant.
I'm running out of ideas.
Bad response from IIS while trying to get new Access Token:
Proper response while developing:
///////Relevant part of log for BAD request
|Duende.AccessTokenManagement.OpenIdConnect.UserAccessAccessTokenManagementService|Token for user test#test.com needs refreshing.
|Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler|AuthenticationScheme: cookie was successfully authenticated.
|Duende.AccessTokenManagement.OpenIdConnect.UserTokenEndpointService|refresh token request to: https://auth.mysite.org/connect/token
|Duende.AccessTokenManagement.OpenIdConnect.UserAccessAccessTokenManagementService|Error refreshing access token. Error = Unauthorized
|System.Net.Http.HttpClient.IdsService.ClientHandler|Sending HTTP request POST https://auth.mysite.org/mycontroller/myaction
|System.Net.Http.HttpClient.IdsService.ClientHandler|Received HTTP response headers after 117.7278ms - 401
///////Same part of GOOD request
|Duende.AccessTokenManagement.OpenIdConnect.UserAccessAccessTokenManagementService|Token for user test#test.com needs refreshing.
|Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler|AuthenticationScheme: Cookies was successfully authenticated.
|Duende.AccessTokenManagement.OpenIdConnect.UserTokenEndpointService|refresh token request to: https://localhost:5001/connect/token
|Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler|AuthenticationScheme: Cookies signed in.
|System.Net.Http.HttpClient.IdsService.ClientHandler|Sending HTTP request POST https://localhost:5001/mycontroller/myaction
|System.Net.Http.HttpClient.IdsService.ClientHandler|Received HTTP response headers after 1994.9611ms - 200
///////Server log during BAD request
Duende.IdentityServer.Hosting.EndpointRouter No endpoint entry found for request path: "/mycontroller/myaction"
Duende.IdentityServer.Hosting.LocalApiAuthentication.LocalApiAuthenticationHandler HandleAuthenticateAsync called
Duende.IdentityServer.Hosting.LocalApiAuthentication.LocalApiAuthenticationHandler AuthenticationScheme: "IdentityServerAccessToken" was not authenticated.
Duende.IdentityServer.Hosting.LocalApiAuthentication.LocalApiAuthenticationHandler AuthenticationScheme: "IdentityServerAccessToken" was challenged.
Okay, found it. Thankfully, looked at Fiddler's WebView and had seen familiar picture!
Then, found this topic. The solution was disabling Basic authentication in IIS settings. Access token request has basic authentication header and it seems like IIS intercepts it. Still a bit unclear why other parts of flow worked.

Amazon SP API getting internal server error

I am trying to get access token from api https://api.amazon.com/auth/o2/token
POST /auth/o2/token HTTP/l.l
Host: api.amazon.com
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
grant_type=refresh_token
&refresh_token=Aztr|...
&client_id=foodev
&client_secret=Y76SDl2F
But after POST request I get 500 server error.
Is it because my app is in draft status? or I am missing something while making request?
If it because of draft status then when the status will get change? any thoughts on this.
Thank you for your help in advance.
The documentation is wrong. I was getting the same exact error and came across this comment on a github issue which mentioned that the data has to be passed into the body of the request, not as query string parameters. Sure enough, this worked for me and I was able to get an access token. So just to clarify: grant_type, refresh_token, client_id, and client_secret should be passed into the body of the POST request to https://api.amazon.com/auth/o2/token and NOT as query string parameters.
Draft status will not keep you from requesting and receiving the access token.
Here are a few things to check as not much can be derived from the example post request from the documentation:
Did you configure AWS IAM role / policy / user properly
Did you use the correct IAM ARN when registering the application
Are you using the correct LWA credentials (I am assuming you're not passing foodev and Y76SDl2F as those are example parameters)
Have you self authorized the application (are you using the refresh token generated
for the authorized application)
Are you 'assuming the role' before the token exchange -- this is a very important step
and is very different in comparison to how access was handled with MWS -- if
you have not, the server will reject the token exchange regardless if the refresh
token is correct. More on that here
This is a non-exhaustive list, just some common issues I have seen other developers have with getting the access token during development, if these don't work you'll need to work with support as they can see the requests hitting the token endpoint.

JIRA Cloud REST API (OAuth 2.0) Error 403 on POST Requests

I am trying to connect my React app to the Jira Cloud API and can't seem to get past a 403 error.
My code currently does a Auth dance using OAuth 2.0 and returns the token and cloudid. I can use this to GET issues, however POST request (like creating an issue) return with 403. I have found here that this error is returned if the user does not have the necessary permission to access the resource or run the method.
I have ensured the user has the correct scope ([write: jira-work, read: jira-work]) and verified this is reflected in the user account (in their account > connect apps tab).
My app is not linked (via ApplicationLink) or installed (via Apps, Manage Apps), is this necessary to perform POST requests?
Here is a sample of my code:
fetch(`https://api.atlassian.com/ex/jira/${jira.cloudid}/rest/api/2/issue/`, {
method: "POST",
headers: {
"Content-Type": 'application/json',
"Authorization": `Bearer ${jira.token}`
},
body: JSON.stringify(data)
})
.then(...)
Neither api version 2 or 3 are working for this POST request. I have explored using Basic Auth however this fails due to CORS errors.
I have verified that the POST request does work in POSTMAN (using the cloudid and token).
---------------------------------------------------------------------------------------------------------------------------
UPDATE
After talking to Atlassian Staff, there is an issue within their API security:
"By trying the same thing you mentioned I think I found what the problem is. Your request likely fails with a ‘XSRF check failed’ in the browser.
I’ve already talked to one of our security engineers and we quickly dived into the implementation code to confirm why this not working and what would need to be changed on our side. We’ve also already opened a engineering ticket to get this addressed. This will likely take a few weeks to get addressed, but I’ll keep you posted if I hear any updates!"
The XSRF check failed was the main error for my 403 response. I'll post any updates I receive and answer the question when a resolution is found.
This has apparently been resolved. Follow the discussion here: https://community.developer.atlassian.com/t/jira-cloud-rest-api-oauth-2-0-error-403-on-post-requests/25621/4

(NodeJS / AngularJS) POST request with 'x-auth' token to server, but token seems to get lost in preflight (no error though)

Background
I have a simple NodeJS server hosted on localhost/Heroku which handles JWT authentication for adding data to the registered user amongst other (unrelated) things.
Here's the GitHub: https://github.com/mlee93dev/pw-keychain-server
I also have a simple Angular2 client on localhost/Heroku for this server:
https://github.com/mlee93dev/pw-keychain-app
Currently, I have my JWT access tokens configured to last only 5 seconds in my server for development purposes.
I have my CORS stuff configured to the best of my knowledge as shown below in server.js:
CORS configuration pic
The Problem
On Postman I test the POST request and I get the expected response - a JWT expiration error:
Postman POST pic
However I don't get the same response on my client - rather, I get a 'JWT must be provided' error:
Client POST pic
As you can see in the pic above, I know I'm actually attaching a token as I console.log it. Here's a pic of the code:
Client POST code pic
So what's confusing me more is that my DELETE request (for logging out) also implements the same x-auth token to request code, and it works in both Postman + client, as seen here:
DELETE error response
DELETE code
So yeah, I'm pretty confused. My guess is I have to configure my CORS some more to allow x-auth header on POST requests specifically somehow? Even though I think it should do that already with my current configuration.
You are providing the body in post request instead of headers.
Angular POST request
So in your post request just do the following
this.http.post(yoururl, {},{headers:new Headers({'x-auth':token})})...
And it should work.

ng-token-auth, ionic, devise_token_auth; token get lost randomly in xhr request

I have inherited a Ionic app which uses ng-token-auth+devise_token_auth to handle the authentication and the session between front and back.
What happens is quite strange. Sometimes (specially with slow connections) the request (or the response) get lost and after that I get only 401 http errors.
I know that that everytime I send a request the token expires, but when the xhr request is cancelled (by the server I suppose, or by the browser, I don't know) the token is expired without having been replaced by the new one generated by devise_token_auth gem.
I know Rails but I'm not familiar with Angular, neither Ionic and I don't know exactly where to look.
After reading a lot of SO answers where noone seems having my problem (which happens locally and in staging/production), I checked the following
storage is set as localStorage.
config.batch_request_buffer_throttle = 20.seconds
there is no pattern between cancelled requests, sometimes I perform get for the username, sometimes a post or a put to a comment.
Is not a CORS problem because it would happen always or never. (moreover I'm using a proxy as explained in ionic blog)
Maybe it could be related to provisional headers chrome bug. But, how can I be sure?
What puzzles my is that it happens only sometimes and not always. (and there are no errors in the backend)
The only workaround I have found in the devise_token_auth documentation is change config.change_headers_on_each_request to false avoiding in this way the regeneration of the token.
But I don't like this solution because I think it hides the real problem in an insecure way instead of solving the token loss. Any suggestion?
Kindly, please check this thing:
Version: which version of this gem (and ng-token-auth, jToker or Angular2-Token if applicable) are you using?
Request and response headers: these can be found in the "Network" tab of your browser's web inspector.
Rails Stacktrace: this can be found in the log/development.log of your API.
Environmental Info: How is your application different from the reference implementation?
This may include (but is not limited to) the following details:
Routes: are you using some crazy namespace, scope, or constraint?
Gems: are you using MongoDB, Grape, RailsApi, ActiveAdmin, etc.?
Custom Overrides: what have you done in terms of [custom controller overrides]
5?
Custom Frontend: are you using ng-token-auth, jToker, Angular2-
Token, or something else?

Resources