What is the workflow for validating a refresh token and issuing a new bearer token? - security

This is not a coding question, but a conceptual question for the correct handling and processing of a refresh token.
I have a single page app which issues a jwt token when logging in. The token works just fine. Now, I want to set the expiration to a low value, and use a refresh token to refresh the bearer token.
The question is, what claims should be stored in the refresh token? And what steps are supposed to be done to validate the refresh token before issuing a new token?
For example, right now my refresh token is a jwt which stores an expiration, so the client knows when the refresh token expires, and a username claim so that I know what user the refresh token is associated with.
So then when the refresh token is recieved:
Check that it is not expired.
Check that it has not been revoked.
Use the UserName in the refresh token to issue a new short-lived bearer token.
Is this the correct workflow for this? I just want to make sure I am not missing any security checks.

If your application is a single page application, you should not use long lived refresh tokens as you have no way of securely storing them.
OAuth2 defines a number of grant flows for different types of clients (which I've described here). Refresh tokens are only meant for confidential clients (like web applications living on a secured server).
Your refresh token is just as vulnerable to theft as your access token, since both are bearer tokens stored on the client.
Some OAuth libraries allow SPA or other non-confidential clients to get a new access token by talking to the token endpoint of the authorization server using a session token in a cookie. As long as the cookie is valid, the user can get a new access token. After that, the user will need to re-authenticate. Of course cookies can be marked secure and http only, making them harder to steal.
If you issue the JWT tokens from the same service endpoint that consumes the access tokens, you could have the client include a nonce in the token request that you hash and include as a claim in the token. The client can send the JWT in the Authorization header and the nonce in a custom header. Your token verification would hash the nonce again and compare it to the claim in the JWT. That way, if your token is stolen is harder to use without the nonce value. Of course, in a targeted attack, your nonce could also be stolen.

Related

JWT tokens: questions best practices and risk of symmetric keys

First a little background on my use of JWT tokens.
Users (via a web frontend) login to my service through a login HTTP endpoint that includes a username and a password in the request body. Two factor authentication will be added in the future, but can be ignored for now.
The API verifies the login information and issues a JWT token in the response. This token is signed with a symmetric key and includes a userId (UUID) that uniquely identifies the user.
In subsequent API calls, the user includes that token in the Authorization HTTP header as a bearer token. The API verfies the signature of the token and then uses the userId to make sure that the user is authorized by checking the roles of the user (stored in a database).
The token can expire, forcing the user to login again, or they can use a refresh endpoint that verifies the token and issues a new one to bypass logging in each time the token would expire.
What are the best practices for JWT authentication/authorization? Are there flaws with my approach? Is there a risk of using symmetric keys here? I am open to suggestions on better approaches as well.

Why does using JWT refresh tokens protect against CSRF during authentication?

I have read a few articles regarding JWT refresh tokens, and how/why they are used. One thing i have seen mentioned here: https://hasura.io/blog/best-practices-of-using-jwt-with-graphql/#persistance and here: https://dev.to/cotter/localstorage-vs-cookies-all-you-need-to-know-about-storing-jwt-tokens-securely-in-the-front-end-15id
is that using refresh tokens mitigates against CSRF attacks. The first article states:
The refresh token is sent by the auth server to the client as an HttpOnly cookie and is automatically sent by the browser in a /refresh_token API call.
Because client side Javascript can't read or steal an HttpOnly cookie, this is a little better at mitigating XSS than persisting it as a normal cookie or in localstorage.
This approach is also safe from CSRF attacks, because even though a form submit attack can make a /refresh_token API call, the attacker cannot get the new JWT token value that is returned.
The second article says something similar:
Although a form submit to /refresh_token will work and a new access token will be returned, the attacker can't read the response if they're using an HTML form
I am struggling to see how this would prevent CSRF attacks as I am thinking the following:
A request to /refresh token from another domain to the users will return new JWT token to the user. I am going to assume this is stored in a HttpOnly cookie (as is done in the first article)
As CSRF does not involve any injection of javascript and the cookie it httpOnly, the attacker can't read the value of the new JWT token.
However, if the JWT token is stored in a cookie again, surely a CSRF attacker can just send another request using this new cookie, with the new JWT token sinde?
If my understanding is correct, I am struggling to see how CSRF attacks are prevented by using refresh tokens. Can someone please explain exactly why refresh tokens prevent CSRF attacks, and why the CSRF attacker can't just use the new JWT the user would receive for future attacks?
It seems to me that the thing that would actually be preventing a CSRF attack would be the use of a sameSite cookie, or maybe using some sort of anti-forgery token.
The new jwt would not be returned from the identity provider as a cookie. That would not make much sense as the client on a different origin would not be able to read it. Instead, the token is passed in the response body, or even the url (usually not the token in that case, but let's not delve into that).
So the idp has its httpOnly cookie to authenticate the user, issues a new token in some way that is not a cookie, and the client stores the token for the appropriate origin (not the idp) in say localstorage. This way, any call to the resource server is not vulnerable to csrf, because the token needs to be explicitly be added from localstorage. The idp can be called by attacker.com to issue a new token ("csrf"), but attacker.com will not have access to the token due to the same origin policy, so it's not exploitable.
Note that even if the new token is returned as a cookie for the idp and read from there by the client, it's still ok, because the idp will do nothing with that token, and the resource server (~api) will not receive it automatically.

Generating refresh tokens and access tokens in node server

I'm building mobile and a web app. Both apps will be talking to a node server. I am using JWT for authentications.
Currently, I have the following code to generate an access token:
const token = jwt.sign({ user: body }, "top_secret");
I have some questions about access and refresh tokens:
How to create a refresh token?
What do refresh token look like?
Can I create a refresh token - similar to the way I'm creating an access token?
Is the refresh token only used to generate a new access token?
Can the refresh token be used as an access token?
How do you invalidate an access token
How do you invalidate a refresh token? Examples I've seen used databases to store refresh tokens. The refresh tokens are deleted when you want to invalidate an access token. If the refresh token would be stored in the database on the user model for access, correct? It seems like it should be encrypted in this case
When the user logs into my application, do I send both access token and refresh token? I read somewhere (can't remember where) that it's not good practice to send an access token and refresh token.
If its bad practice to send both access and refresh tokens, when do you send a refresh to the client? Should there be an endpoint where the clients request an access token?
What's a good expiry time for access tokens and refresh tokens?
Please note that in typical OAuth2 scenarios, the server issuing tokens (authorization server) and the API server consuming access tokens (resource server) are not the same. See also: Oauth2 roles.
To answer your questions:
How to create a refresh token?
You generate a string of sufficient entropy on the server and use it as a primary key to a database record in the authorization server. See refresh token syntax.
What do refresh token look like?
From https://www.rfc-editor.org/rfc/rfc6749#section-1.5,
A refresh token is a string representing the authorization granted to the client
by the resource owner.
The string is usually opaque to the client.
Can I create a refresh token - similar to the way I'm creating an access token?
You can, but refresh tokens are typically not structured tokens (like JWT) since they're consumed by the same server that issued them.
Is the refresh token only used to generate a new access token?
yes
Can the refresh token be used as an access token?
no
How do you invalidate an access token
Unless you're using introspection tokens, there's not a good way to invalidate them. Just keep their lifetime short.
How do you invalidate a refresh token? Examples I've seen used databases to store refresh tokens. The refresh tokens are deleted when you want to invalidate an access token. If the refresh token would be stored in the database on the user model for access, correct? It seems like it should be encrypted in this case
Delete if from the authorization server store. If the refresh token cannot be found on the server, it cannot be used to refresh an access token. A refresh token is typically just a primary key to a database record holding data about the client, user and expiration of the refresh token. While you don't want to leak your refresh token, it typically does require the client using them to present client credentials to use it.
When the user logs into my application, do I send both access token and refresh token? I read somewhere (can't remember where) that it's not good practice to send an access token and refresh token.
The user signs in at the authorization server. It returns an access token and refresh token (if your client is confidential) to the client. The client uses the access token alone to access your data on the resource server.
If its bad practice to send both access and refresh tokens, when do you send a refresh to the client? Should there be an endpoint where the clients request an access token?
Your client uses the refresh token in a call to the authorization server to get a new access token. So your client sends only the access token to the resource server and only the refresh token to the authorization server.
Whats a good expiry time for access tokens and refresh tokens?
That depends on your threat model. When your refresh token expires, the user is forced to authenticate again. Some products use refresh tokens that never expire, others use refresh tokens that are only valid for hours or days.

Logout from multiple systems in SSO (Single Sign On)

I am implementing SSO for our systems in order to centralize the user authentication and authorization, in which we will have a SSO-server (User and Session Manager) where the user logs in using his/her credentials and then will be able to access all other associated systems.
The implementation of SSO:
First the user will get the session (access token + refresh token)
and they will be stored in the client side.
If he redirects
to the other systems a (single use token) will be generate by SSO
server for that system
And up on the system loading the (single use
token) will be exchanged with a pair of access-token and refresh
token and they will be stored in the client side of that particular
system
And on each server request the session (access token +
refresh token) will be sent through request header so that the
system's server could request this user's authorization from SSO
server.
Access token has less expiry time than refresh token and it's not stored in SSO server and only it's signature is checked for authorization but the refresh token is stored so that we could revoke it later if needed.
(due to the huge amount authorization requests that we will have later on I did not want to stored the access token.)
The problem is that if a user wants to logout, all his/her access tokens should be expired but they are not stored in database and only in client side for each system and I can only revoke the refresh token so the token remains valid until it's expiry time passes and till then it can be used and it means the user is still login.
I use JWT for the token generation and verificaiton.
This is my first question in here I hope I have explained the problem properly.
And I will be waiting for your kind responses.
Preferably use a cookie to store your tokens. When the user has logged out. Simply clear the cookie and return. Now the user does not have the access token and won't be authenticated.
Note: Make sure to make a secure cookie.

Using Refesh Token in Token-based Authentication is secured?

I am building a token based authentication (Node.js using passport/JWT with an angular client).
After the user enter his credentials he gets an access token, which he sends in every request inside the header (header: bearer TOKEN).
I don't want to prompt a login request everytime his access token expires (about everyday I guess),
I've heard about the Refresh Tokens. The refresh token never expires (or rarely expires) and able to renew tokens indefinitely.When the access token is about to expire, the client can send a renew request to get a new access token by sending his refresh token.
I don't understand few things, I might be missing something:
How a long-living/never expiring refresh tokens don't ruin the security of having short-living
access tokens.
Cookies can be stole and be used until they expire. Tokens are short living so they more secured,
but if I provide a long-living refresh token I lose the advantage of using tokens.
NOTE: I am aware that the refresh tokens are sent at the initial login, so cann't be spoofed in every request, but if they are spoofed at the initial request they are vulnerable.
The refresh token is presented on a different path than the access token: the access token is only ever presented to the Resource Server, the refresh token is only ever presented to the Authorization Server. The access token can be self-contained so that it does not need costly calls to the Authorization Server to check its validity, but to mitigate loss and to increase accuracy (it cannot be revoked in case something goes wrong) it is short-lived. The refresh token is long lived and gets validated on each call to the Authorization Server and as such it can be revoked. The combination of the two makes the system secure.
I use the following approach:
Tables/indexes:
User table (just has the user ids and all the user related meta-data)
JWT table (three fields : user_id, access_token, refresh_token)
Authentication Flow
1.When a previously unauthenticated user signs in, issue a JWT which contains an access token, and a refresh token. Update the refresh token in the JWT table, together with the user_id, and the access token.
2.Make sure that the JWT has an expiration time that is something small/comfortable for your users. Usually less than an hour.
4.When a client makes a request with a JWT
a. Check expiry of the access token. If the token has not expired -> continue without hitting any db tables.
b. If the access token has expired, lookup the user_id in the JWT table, and check if the refresh token and access tokens match, whatever the client has provided,
If yes, issue a new JWT with the response and update the new refresh token,access token into the JWT table.
if no, return 401. The client is forced to ask the user to then sign in.
END.
To summarize,
1.DB calls are required only to check if the refresh token is valid.
2.This system allows for a user to sign in from any number of devices, with any number of JWT's
3.All JWT's related to a user can be invalidated, by wiping the refresh tokens related to that user from the JWT table, this can be done, for eg: when a user changes his/her password. This, in effect, narrows down the window of compromise to the expiration time of the access token/JWT.
I believe this is the intention behind JWT's. The percentage of DB calls/user depends on your expiration time, the duration a user is usually on your website, etc.

Resources