Why should I send token in `Authorization: Bearer ` header? - api

I am new to API development. Currently I pass my access/auth token in request body. For eaxmple,
{
status:true,
token:"<thetoken>"
}
But, When I refer about API security, They use Authorization header to pass the token.
My question is, What will happen or Whats wrong, If I send token in request body?
-- Thank you ❤ ---

First of all, securing API endpoints is a solved task. Instead of inventing your own authorization protocol, I suggest you to have a look at already existing industry standards like the OAuth 2.0 Authorization Framework (RFC 6749).
Following standards makes sense for multiple reasons:
they are widely known and battle tested
reference implementations and libs are available
you can stand on the shoulders of giants and focus on your business logic
etc.
However, there is nothing wrong with sending an access token in a request body. In RFC 6750 the OAuth 2.0 protocol defines all possible bearer token usages including sending the token as a Form-Encoded Body Parameter. Make sure to read carefully and take the security considerations into account.
Long story short: It does not really matter how you hand around access token, as long as you follow the standards.

Related

Appropriate HTTP status for redirecting to authentication in a REST api

I'm kind of surprised that, after searching for this for a while, I didn't find as many answers as I thought would be out there (well I found none), so maybe by asking it here we can help improve search results.
I'm building a REST api which has JWT-based authentication. There is an /auth/login route which returns the token after login/password verification, and the token is subsequently sent in every route in a Authorization http header.
Not, suppose that someone queries another route (say, /cars), without sending the token (that is, before logging in). If I return a 401 unauthorized, I can make the frontend query /auth/login to get the token.
But, strictly speaking, this does not conform to the REST specification, because every resource should be discoverable from the initial one, and a client accessing /cars and receiving a 401 will not know about /auth/login.
So another option would be a redirection like 302. But this semantics means that the resource was temporarily moved, and this is not the case (the resource is still /cars, you just need to authenticate first).
So, what is the correct way to do this procedure in a "true" rest api?
I 100% agree, and that's why I proposed this standard:
https://datatracker.ietf.org/doc/html/draft-pot-authentication-link-01
The idea is that for cases like this, you should be able to return a Link header with an authentication rel, so the client can discover how to proceed.

How (if at all) should I encapsulate an access token on client side?

I'm starting a new project which will have to manage many access tokens for many different APIs. So I was wondering if it was good practice to provide the access tokens to the different classes implementing the API calls or if the tokens should be better encapsulated.
Currently, I see two options:
every API class constructs their own requests (mostly HTTPS requests), gets the access token from an authentication interface and adds that token to the request in a manner required for that API
the authentication interface accepts the request from the API class and adds the token to it before actually dispatching the request.
With the latter option, the API class would never see the token, but it would be difficult to foresee all the options how to add the token to the request (header, GET parameter, or totally different ways).
What should be best practice in this case?
Generally an access token contains information such as "is this user privileged" and other authorization-related claims that go beyond authentication.
That means that the authentication service alone cannot deal with these claims, and the API class needs to be able to see them.
Therefore, your API classes should have the opportunity to add claims to the access token. Whether or not they are the ones constructing the token itself is not important.

How to get identity in API using OpenID Connect

I'm trying to follow OpenID Connect best practices. For the simple scenario of calling API from application the OpenID Connect suggest to pass the Access Token (which is not included user identity), and if the API in some points need the user identity it should call /userinfo endpoint of OpenID Connect provider.
So the question is: Is it the best way to get the user identity in API?
Assume I have an end point named CreateOrderForCurrentUser() so each time any user call this api I need to call the /userinfo endpoint, it seems too much cost for calling an api.
Why I don't pass the Identity token to the API?
Or Why I don't put some identity claims in Access token?
Should I use HOK Token instead of Access token?
Any idea please.
It seems here is kind of same as my question: Clarification on id_token vs access_token
And he respond in comments: https://community.auth0.com/t/clarification-on-token-usage/8447#post_2
Which as my understanding means: put some identity claims in Access token (Custom Claims) and rely on that in the API.
But still it doesn't make sense. The OIDC insist to not use Access token as Identity and now we are going to add identity claims inside Access Token. Could any one clarify that?
ID_Token is used for your client app tells the app who you are , the audience of the ID Token is the id of your client app , with access token , API/resource knows whether authorized to access the API and perform specific actions specified by the scope that has been granted.
By default , it will include user identifier in access token(sub claim) , so you should know which user when calling CreateOrderForCurrentUser function . You could customize the access token to include more user related claims if needed . But i would suggest to simplify the access token , and you could use access token to acquire user information by invoking user's API endpoint .
I asked the same question in Auth0 Community and there is a discussion about it that might be helpful for others who have the same issue.
I copy the same answers here:
markd:
You are correct that you should not use an access token as proof of identity, but before you get to your API you should have already authenticated the user and received an id_token for them. If you have already authenticated the user via OIDC, as far as I know there’s nothing wrong with adding custom claims to the access token to pass data to your API. Your API could also use the client credentials grant type to pull data from Auth0.
Me:
I’m looking for the best practices. I want to be sure adding identity claims to the access token and rely on that in API does not broke any thing and is based on best practices or maybe the best practice is always call the /userinfo endpoint in API and don’t rely on Access token identity claims.
The API doesn’t know about the authentication process and don’t care about that. Any one any how pass the signed Access token to the API, it would be accepted. Now in API point of view is that proper way to rely on identity claims in Access Token? I have doubts. But I would be happy if we could ignore calling the /userinfo end point each time.
jmangelo:
I can share some (hopefully) informed views on this subject, but please do take them with a grain a salt and question stuff you disagree with or you don’t consider clear enough. When it comes with software the devil is on the details and in the security landscape it’s even more true so you need to consider best practices as what will likely be recommended for the majority of the scenarios and also what will likely be less risky; it does not mean that nothing else is possible.
For example, although the recommendation is indeed to use access tokens in requests to API’s this does not mean that there isn’t a specific scenario where technically it would also be okay to send an ID token instead.
Focusing on your particular questions and starting with the last one (3); we should not compare HOK and access tokens because they are not at the same level. In other words, you could question if in your scenario you should use bearer tokens or HOK tokens as this way and using the terminology of your linked page you would be choosing between two token profiles where each give you different characteristics.
At this time, the access tokens issued by the Auth0 service as part of API authorization are bearer access tokens so this question has only one answer if using the Auth0 service.
Jumping to the first question; it’s not that you cannot pass the ID token to the API, it’s just that the scenarios where that would be adequate are much more constrained. For example, an ID token is issued with the client identifier as the audience; it’s common to have multiple client applications so you have just coupled your API to how many client applications you have, because assuming you will validate the audience of the ID token, your API would now need to know the identifiers of every client.
For question (2) which I assume is also interested in why call /userinfo if you can include claims in the access token. I believe this can depend a lot on requirements and/or personal preferences. At this time the only format supported when issuing an access token to a custom API is the JWT format.
The above means that you have a self-contained token that once issued the API can mostly validate independently which is great in terms of scalability because the API does not need to make (frequent) external calls for validation purposes.
However, being self-contained this immediately means that any data you include directly in the token will be considered the truth for the lifetime of the token itself. If instead the API is calling /userinfo or even the Management API directly then you ensure fresh data at the cost of network overhead.
In conclusion, in my personal view the choice between network calls and embedded claims is more tied to the characteristics of the data you are interested in that just from a best practices point of view.
As a final note, even without any addition of custom claims an access token issued by the service in association to a custom API already conveys user identity. In particular, given the access token is a JWT, the sub claim will contain an identifier that uniquely identifies the end-user that authorized the current application to call the API on their behalf.

Json Web Token + User Authentication

I just implemented Json Web Tokens to my api, but I don't understand how to verify if the user that created the token, is the one that is making the request.
For example, I have the /user/login end point, and I received the user and password for login. Then I create a json web token with the user data inside, and return it. And here is my problem, how do I know that the user that create that token, is the one that is making the request ?.
I found several ways to verify this, for example saving the user-agent + ip of the user and only accept request for that token if the user-agent + ip is xxx, but I am not really sure that is the best way.
I hope you can help me with some tips,
Thanks for all
how do I know that the user that create that token, is the one that is making the request ?.
Because the JWT includes the user ID and is signed, therefore any alterations to the content will be detected. Possession of the token is proof of authenticity
The process of issuing and authenticating with JWT is more or less like this
Issuing new JWT
User performs and authentication using its credentials
The server validate credentials, generate the JWT payload including the user data and some fields such as expiration time or issuer, and signs the token with server private key
The client receives the token and store it (in a secure storage).
Authentication
User sends a request to server. The request includes the JWT, usually in headers or as url param
The server validates the signature with the key, and extracts the user ID to know the requestor. If the signature is not valid rejects the request
Any reason you can't use a standard like OAUTH2 and let the big boys handle security for you? Rolling your own security is usually very difficult to get correct and almost all the major players provide free OATH support.
That said, I'd be hesitant to lead you down a bad path, however I've been in your shoes before so if you must roll your own security, make certain you fully read all of what OWASP has to offer. They offer very detailed threat analysis and also give suggestions that will be invaluable along your journey.
OWASP Threat Analysis
EDIT 1
A good light weight and easy to implement standard is OpenID which as their banner explains is,
A Simple Identity layer on top of OAuth 2.0
See here for a very detailed explanation of how it works:
OpenID-Wiki

What difference is token in header and body?

I found a doubt when I was designing API. Some documents guide developers how to make and deal with token.
If I will access a website requiring token authentication, I should set my token in HTTP header, let service ascertain my validity.
Although I think designing setting up method can be flexible, for examples, setting in header or body, I don't know what difference are they?
In this token case, because token is secret info, is setting in header safer than in body? or setting in header can't make HTTP be a burden? What information does it fit with setting in header?
It's no special when data sets in header or body.
Except you have specail data needs to set in header, and then your web application only accepts the specify method to do. It follows you how to desgin the processing workflow.