How can a resource server validate an access token without the authorization server - jwt

I'm learning about access tokens and refresh tokens. I understand...
An access token is an artifact that proves the user has been authorized to access a resource and allows a client application to perform specific actions on behalf of the user.
A refresh token is an artifact that lets a client application get new access tokens without having to ask the user to log in again.
I don't understand the following paragraph from this JWT book:
The key aspect of the separation between access and refresh tokens lies in the possibility of making access tokens easy to validate. An access token that carries a signature (such as a signed JWT) may be validated by the resource server on its own. There is no need to contact the authorization server for this purpose. Refresh tokens, on the other hand, require access to the authorization server.
The text is referring to the following image:
What exactly does "validate" mean here? How can the resource server validate the access token on its own? If the authorization server generates the access token, which it does in this case, isn't the authorization server required to validate the access token?
The only thing I can think of is that the resource server has a copy of the key used to sign the access token (see here). If so, doesn't that render the authorization server redundant?

JSON Web Tokens can be validated because, as you guess correctly, the resource server will have beforehand the public key of the private key that was used to sign that token. It means, that if someone in the middle tried to tamper the JWT, the validation will fail and the JWT should not be processed.
Also, the JWT contains fields as the expiration time that can be checked by the resource to understand if the token is still valid or not.

Related

What is the MUST have claims for JWT refresh tokens? Can it be identical to the access token (with a longer exp)?

Im playing around and creating a custom access token system using JWT. I have already created a system for signing and validating JWT access tokens.
However, I find it hard to obtain information about what claims a refresh token should consist of.
Should i create refresh tokens identical to the access token - with a longer expiratiom time so that the same function that validates access tokens can be used to validate the refresh token?
A refresh token is typically an opaque value that is only used by clients to refresh access tokens. The flow works like this:
Web or mobile client implements OpenID Connect to authenticate users and get tokens - prompting the user to consent in some cases
An Authorization Server (AS) issues the tokens and stores details of this 'delegation' in a database - tokens are a pointer to this state
Client sends access tokens to APIs until a 401 expired response is received
Client then tries to refresh the access token by sending the refresh token to the Authorixation Server, which then looks up claim details from the stored state
I would make sure you get these responsibilities right - in particular avoid building your own AS and use a free one provided by experts, such as Curity Community Edition. Many security solutions will then be easier to develop.

How does all services in microservice architecture (token based) know that the user has logged out?

When a user logs out (sign out) of the application, how does the gateway communicate to all services that the user has logged out?
In other words, what happens when a user logs out in microservice architecture application?
This is generic question, I will give my personal thoughts.
Let's take a Single page application, talking to bunch of Microservices and secured by a Gateway that validates the token.
When user logs in, token given by auth server is stored within browser storage(ex: localstorage).
When user log out, no communication is sent to Gateway or auth server, tokens will simply be deleted from browser storage.
So, if someone gets hold of access tokens, they can be used to call services as long as access tokens doesn't expire.
This is typically why there are two tokens given by auth server, an access token and a refresh token. Access token which is used to secure apis expires pretty quickly and a refresh token which has much longer expiry time can be used to get new access token.
As you've included the JWT tag, so I'm trying to give the response by considering that only. The JWT token is a self-sufficient encoded token that contained certain attributes including an expiration period. The sole purpose is to provide stateless authentication. Authentication service usually returns two token, access_token and refresh_token. Client store both of them in some storage on their end. Access token usually issued for a very short span of time and so the client can use the refresh_token in order to get a new access_token on the expiration of the latter. One can access the services until refresh_token get expired. After that client has to go through the authentication process to get new tokens. In case when user logout from the system client should remove both of the tokens from its storage. Because as there is no state maintain in the case of JWT, the server can still accept the old token until they're not expired.
Validation of token for expiration and integrity should be done at the gateway level.
One can avoid the use of the token for service to service communications as those are internal services and running in a private network although one can do the same validation at this level too.
So in case of user sign out, the user's auth token should be removed from the client-side and the gateway should not communicate to other services. There are other special cases where token revoke is a particular case that could be handled by taking the help of distributed cached store in scaleable authentication systems.
A token-based service can generally infer the following from a token -
Who made a request?
Upto what time this token is considered valid?
Which actions are allowed when using this token?
A token based service just accepts or rejects a request depending on provided token, regardless of whether it is a user or a machine making the request. A logged-in user is just someone who can perform actions which this user is authorized to do. A token is a limited representation of such a user.
My point being, it is the application telling the user that they are logged in (have a token it can still use), or logged out (no token yet, or expired). Such a token is obtained by authenticating to the service using ones username and password.
Answer is based on my knowledge, so everyone, please do point out mistakes if any. I don't know in detail about aws api gateway stuff, so maybe someone else can brief you on it in case it works differently.

Using both access and refresh tokens for refreshing them

Was investigating how to work with JWT and found not obvious thing for me:
Why for refreshing access token are not using both access and refresh tokens but only refresh token?
In this case we will be able to:
Verify access token signature, even if it is expired.
Get from access token information from payload, which may help in finding refresh token in database.
Your question is a bit unclear and is assuming some things that may not be true. Neither access tokens not refresh tokens have to be JWTs and JWTs are not specific to OAuth2 (which defines access and refresh tokens, but doesn't say how they should be implemented).
The audience for access tokens and refresh tokens is also different - access tokens are sent to a (possibly separate) resource server (the issuing authorization server may not even have kept a copy if they are self contained). Refresh tokens are sent to the authorization server.
Locating either type of token in a database (assuming they aren't self-contained tokens like JWTs) should never be a problem because they should be unique tokens which make ideal primary keys for a database table. So there would be no reason to send an expired access token as part of a refresh request.
Welcome to Stack Overflow, by the way :).

OIDC - What's to stop someone from spoofing a JWT access_token?

When you authenticate with an OIDC provider you get back an id token and if you specified scopes for an API you get back an access token so that client applications can make requests to protected resources on the end user's behalf. Typically the access token is also a JWT.
But what is to stop someone from spoofing one of these access tokens, and creating one and passing it to an API? I understand there are safeguards to prevent modification because the signature will be different than what any validation logic is expecting, but what if a malicious user created a brand new one manually? Especially because these tokens can be validated 'in place' by any API that requires an access token (not all API's use the introspection endpoint... especially with a JWT). I do understand there is metadata around the signing keys for JWT's from OpenID Connect providers and that it is available in the OIDC discovery document. For example, here is Google's JWK metadata. Given that you have signing information publicly available, and JWT access token's can be validated without any requests to the OIDC provider, how are JWT's secure? What is preventing a person from creating one and passing it as a bearer token to an API that requires an access token?
But what is to stop someone from spoofing one of these access tokens, and creating one and passing it to an API?
Spoofing and reconstruction of signature is nearly impossible without the private key (assuming you are using asymmetric signing algorithm like RS256) that used for signing the original JWT.
The JWK information available via OIDC discovery document only contains the public key.
Also Use HTTPS for authorization / token exchange to avoid token sniffing.

Facebook OAuth 2.0 "code" and "token"

Why do you need both a "code" and a "token" in the Facebook OAuth2 authentication flow as described here: https://developers.facebook.com/docs/authentication/ ?
If you look at the OAuth dialog reference (https://developers.facebook.com/docs/reference/dialogs/oauth/), it seems like you only ever use the token to fetch information about the user, and if you specify the response_type parameter as token or code,token, then you get the token on the first time.
Why do you need to get a "code" and then use the code to get a "token" as opposed to getting the token directly?
I guess I'm misunderstanding something basic about how OAuth works, but it seems you avoid the request to https://graph.facebook.com/oauth/access_token entirely if you get the token the first time with the dialog.
Let us take a simple example to differentiate authentication code vs access token.
You as a user want to try a new Facebook app called Highjack.
So you click on the application and the Highjack app asks you to log into your Facebook account. When you are done, Facebook generates an authentication code for you.
This code is then passed to the Highjack server which uses its own FB client id, FB secret and your authentication code to get an access token.
In the above example the authentication code is confirming you as a user is a valid FB user. But the second steps says "you as a FB user is giving access to the Highjack app for certain resources".
If the Highjack app wanted implicit grant (i.e direct access token), then the access token would be visible to you also since it is being exchanged with the browser. This means you can now call all Facebook APIs on behalf of Highjack using the access token. (You can only use the access token to get your personal information but Facebook has no way of knowing who is calling their APIs.)
Since we have 2 parties (You and Highjack) authenticating with Facebook we have this 2 fold mechanism.
Borrowed shamelessly from Salesforce Documentation:
Authorization Code
An authorization code is a short-lived token representing the user's access grant, created by the authorization server and passed to the client application via the browser. The client application sends the authorization code to the authorization server to obtain an access token and, optionally, a refresh token.
Access Token
The access token is used by the client to make authenticated requests on behalf of the end user. It has a longer lifetime than the authorization code, typically on the order of minutes or hours. When the access token expires, attempts to use it will fail, and a new access token must be obtained via a refresh token.
From the OAuth 2.0 Spec:
The authorization code provides a few important security benefits
such as the ability to authenticate the client, and the transmission
of the access token directly to the client without passing it through
the resource owner's user-agent, potentially exposing it to others,
including the resource owner.
So, basically - the main reason is to limit the # of actors getting the access token.
"token" response is intended primarily for clients that live in the browser (e.g.: JavaScript client).
Answer) You need/want both the code and token for extra security.
According to Nate Barbettini we want the extra step of exchanging the authentication code for the access token, because the authentication code can be used in the front channel (less secure), and the access token can be used in the back channel (more secure).
Thus, the security benefit is that the access token isn't exposed to the browser, and thus cannot be intercepted/grabbed from a browser. We trust the web server more, which communicates via back channels. The access token, which is secret, can then remain on the web server, and not be exposed to the browser (i.e. front channels).
For more information, watch this fantastic video:
OAuth 2.0 and OpenID Connect (in plain English)
https://youtu.be/996OiexHze0?t=26m30s (Start 26 mins)
If you look at the flow of Authorization Code OAuth type, yes, there are actuary two steps:
<user_session_id, client_id> => authorization_code
<client_id, redirect_uri, authorization_code, client_secret> => access_token, refresh_token
In step1: the user tells the OAuth Server that "I want to auth this client (client_id) to access my resource. Here is my authentication (user_session_id or what else)"
In step2: the client (client_id) tells the OAuth server that "I've got the user the authorization (authorization_code), please give me an access token for later access. And this is my authentication (client_id & client_secret)"
You see, if we omit step 2, then there is no guarantee for client authentication. Any client can invoke step1 with a different client_id and get an access token for that client_id instead of its own. That's why we need step2.
If you really want to combine step1 and step2, you can do something like this:
<client_id, redirect_uri, client_secret> => access_token, refresh_token
We use this approach in our Open API Platform, and we haven't find any security problem yet.
BTW, there is actually an Implicit Grant type, that is:
<client_id, redirect_uri> => access_token, refresh_token
It is generally applicable to client only application which have no server backend. In that case, the OAuth server must ensure that the redirect URI belongs to that client (same with the register redirect_uri, for example).
The mix-up came because the user on behalf of himself and not the client app authenticate against the authorization server (i.e. facebook).
Its much simple to secure the client app (with https) then the user-agent (browser).
Here is the original formulation from IETF-oauth (https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-threatmodel-08#section-3.4):
3.4. Authorization Code
An authorization code represents the intermediate result of a
successful end-user authorization process and is used by the client
to obtain access and refresh token. Authorization codes are sent to
the client's redirection URI instead of tokens for two purposes.
Browser-based flows expose protocol parameters to potential
attackers via URI query parameters (HTTP referrer), the browser
cache, or log file entries and could be replayed. In order to
reduce this threat, short-lived authorization codes are passed
instead of tokens and exchanged for tokens over a more secure
direct connection between client and authorization server.
It is much simpler to authenticate clients during the direct
request between client and authorization server than in the
context of the indirect authorization request. The latter would
require digital signatures.
Theoretically,
Access Tokens cannot tell us if the user has authenticated but auth code does.
Auth code should not be used to gain access to an API but access token should be.
If you have a single page application or mobile application with no or minimum backend, your application may want to access user's FB data directly at frontend. Hence the access token is provided.
In another case, you may want a user to register/login to your app using some external auth service provider like Facebook, Google etc. In this case, your frontend will send the auth code to the backend that can be used to get access token from Facebook at serverside. Now your server becomes enabled to access user's FB data from the server.
Basically, as an extension of Lix's answer, the access code route allows a Resource Owner (i.e. the Facebook User) to revoke authorization for their User Agent (i.e. their browser), e.g. by logging off, without revoking authorization for an offline Client (i.e. Your Application).
If this is not important, then there is no need to use the access code route.
Furthermore, the access code is provided to ensure that the Token provided to a server is actually registered to the Resource Owner (i.e. the Facebook User), and not the User Agent (or a Man-in-the-Middle).
This seems similar to the question of either choosing the implicit vs authorization code grant flow. In fact, here is what looks like an opposite view point?!.
Also, as Drew mentioned,
When the access token expires, attempts to use it will fail, and a new access token must be obtained via a refresh token.
another piece is the refresh token, but I don't see that being explained too well in the FB Docs. If I'm correct, the implicit grant (the direct token) should be really short lived, but that is to-be-enforced and FB.js seems to hide a lot of that (this one I have not looked as deep into).
If I'm correct, the code%20token is an optimization allowing both the User Agent to have a token and allowing for the server to initiate the token exchange process in a single request (as anything over Network IO is considered expensive, especially to a User Agent).
In OAuth 2.0 with facebook, the overall concept is simple as follows.
Step 1. Obtain "Authorization Code" by a GET request
request URI: https://www.facebook.com/dialog/oauth
Params:
response_type=code
client_id={add your "App id" got by registering app}
redirect_uri={add redirect uri defined at the registration of app}
scope={add the scope needed in your app}
Headers: None
Step 2. Obtain the "Access Token" by sending the authorization code as a POST request
URI: https://graph.facebook.com/oauth/access_token
Params:
grant_type=authorization_code
client_id=<add your "App id" got by registering app>
redirect_uri=<add redirect uri defined at the registration of app>
code=<obtained authorization code from previous step>
Headers:
Authorization:Basic encode <App Id:App Secret> with base64
Content-Type:application/json
Step 3. Use the access token got from above step and retrieve user resources
It’s because the access token is given to an AUTHENTICATED client (third-party app) using a shared secret that only FB and the client knows. The only way that the user could directly request the access token is by knowing the shared secret, which would make the secret public and could lead to a man-in-the-middle attack. Further, while FB can guarantee a secure connection to the user, FB can’t guarantee the handoff of the token to the client is secure. However, FB (and OAuth2) does require a secure connection between the client and FB. The access token is tied to the client public ID (usually hashed), which means only the original client application can use it to request the token because the secret is sent along with the authorization code to get the access token.
You recieve a token when the user logs in. But you might want to change the token when you are performing other actions. EG posting as your app/page or posting as a user with offline_access.