Custom (Non-OAuth) Refresh Token Implementation - authentication

I'm working on an application that uses a token-based authentication system, where the user provides their username / password and receives a token in return (the token gets saved to the database as well). Then subsequent requests will include this token as a custom header and we can use this to identify the user. This all works fine.
Right now if the user doesn't login for 3 days, we expire the token. I was reading a little about refresh tokens in OAuth and I was wondering if I could somehow implement something similar. i.e. when providing the auth token, I also provide a refresh token which can be used later to request a new auth token. In terms of security though, it seems quite similar to just never expiring the user's auth token in the first place. Should I be sending additional information with the refresh token to validate the user?

In OAuth2, the resource server and authorization server are often not the same.
The refresh token is sent back to the client when the access token is issued and when the token is refreshed. The client needs to authenticate itself (using client id and client secret) to use the refresh token. The resource server never sees the refresh token.
Also, access tokens are not stored at the server side as they have a limited lifetime. Refresh tokens are stored and can therefore be revoked.

Related

JWT Auth, Way to access AccessToken when you logged in

i'm having a diffculty with Access Token.
And i'm new in web dev, taking a role in front-end.
So far, my web site is connected with server for log in API, and i can verify user infomation after logged in at console.
However, i'm wondering the way to get access to Access Token which is issued from the server.
So, the logic is as follows,
When i sucess logged in with correct user information, AccessToken and Refresh Tokens are issued.
I needed a code to access to Access Token, so if i have, i can access to prevented pages (such as, MyPage)
The Access Token has 30min of expires, so after logged in 30min,the issued Access Token must be expired and lost its access rigth to private pages.
Summary !
I'm wondering the way to code the AccessToken in Client side to server side after logged in. Found some of informations that saying include Access Token in headers request in Client side.
How can i code whether the Access Token is expired after 30 min and reqesting again to issue the access-token when i access to private pages with access-token expired state.
Then, if server can find there is a refresh-token in Client side, then issues access token very easily.
Wondering should i put all of the pages that check wether AccessToken is alive?
Normally, it handle by token middle-ware between front-end to IdP(ID provider) server.
It automatically refresh the access token by refresh-token.
The middle-ware's roles
refresh token together with the access token when the user login is processed.
access token and refresh token are re-issued when the refresh is executed
saved the access token and refresh token into local storage (usually called cookies)
If an access token is expired when you execute an API, it will be able to execute the API with a new access token if a refresh token is valid
If an refresh token is expired when you execute an API, it will be able to execute the API with a new access token if a refresh token is expired after got new refresh token.
Popular IdP is Keycloak provides middle-ware for multiple languages.
Java, Javascript, Python, Spring Boot, Angular, React
sorry, I missed your question
I'm wondering the way to code the AccessToken in Client side to server side after logged in. Found some of informations that saying include Access Token in headers request in Client side.
The front-end access an access token and decode it for getting user's information, role and expires time
How can i code whether the Access Token is expired after 30 min and reqesting again to issue the access-token when i access to private pages with access-token expired state.
middle-ware takes care the life time of access token
Then, if server can find there is a refresh-token in Client side, then issues access token very easily.
Yes,
Wondering should i put all of the pages that check wether AccessToken is alive?
It stored in local storage in single place and use it from mutiple pages
There are a few things I might not agree with in #BenchVue answer:
Client should retrieve user data from ID-tokens only. Access-tokens audience are resource-server(s), can be opaque and should be used only as authorisation headers.
Authorization-server (middle-ware in the answer) defines tokens expiries. It does not refresh it auto-magically. Clients must handle tokens refreshing, which can be done pro-actively as OAuth2 token responses contain expiry in adition to the token itself (even for opaque token).
Do not code a gripped weel. Pick a lib. You're very very likely to make security breaches otherwize. Plus you'll waste a lot of time implementing stuff like:
redirection to authorization-server for login / logout when user tries to access a protected route
silent access-token refreshing (just before it expires) using refresh-token
JWT adding as Bearer Authorization header to secured resource-server
etc.

JWT auth flow using access token and refresh token

I'm working on a project (nothing production-level, only for leveling up my skills) and I'm using JWT to handle authentication.
From what I've read, using a JWT only as an access token is quite unsafe, and hence we need refresh tokens. So, on login, the server returns an access token and a refresh token (which I will be storing in an httpOnly cookie). The access token expires in a short time, but the refresh token is used to get a new one when it does.
My question is, when do we use the refresh token to get a new access token? Is it when the user wants to get a protected resource and finds that the access token is expired (and the refresh token has not) or do we send a new access token each time the user wants to get the protected resource? I'm confused about when and where the refresh token comes into play.
(I'm using React for the frontend and Nodejs for the server)
You're using some security token so it mean that your system has some protected resources. Those resources can only be accessible on successful validation of the token. As you're using the JWT Token (usually for stateless authentication) and your system is granting both access_token and refresh_token to the client, so on server side you can use some authentication interceptor to validate the access_token in the each private request and return some error code on token expiration. On the client side you could also use some filter which should capture the error code and by utilizing the available refresh_token it should request for new access_token from the server. In case of refresh_token expiration your system should follow the route of fresh authentication.
The refresh token can be used at any time to request a new access token. Checking the validity of the access token before he request is one way of accomplishing that. Another common practice is to refresh the access token if it is within a certain timeframe of the current token expiring. A simple cronjob can work in this case. If you assume the access token is not used in multiple places (which it shouldn't be) then the current access token can be invalidated when the new access token is created. Also, for maximum security, the refresh token should be replaced with the access token. This limits security risk around a long-living refresh token becoming compromised.

Best practice for generating refresh token with JWT

Background
I'm implementing an authentication system based on JWT and Refresh tokens but I had an hard time searching for serious documentation about the refresh token generation and handling.
The common scenarios I've found expect:
A short-live token JWT that is stateless and not stored on the server-side
A long-live refresh token that is stored somewhere on the client side and on the server-side and that allows to get new authorized JWTs.
Refresh token generation
My first question is about the refresh token generation. I've seen two main scenarios:
The refresh token is a simple random string or a uuid that it is stored (with its expiring time) on the server side and represent a long user session
The refresh token is itself a JWT containing the not-sensitive data of the user that has logged in and has itself an expiration
The first case is the simplest but allows to encapsulate session data only manually, the second case is more complex but allows to encapsulate the session data, the expiration and it is generated only by a secret held in the server (it means more security). In this last case, however, making the JWT persistent is against the JWT phylosophy and more effort is required for validating also this JWT and comparing the data.
Refresh token workflow
Prerequisites
Storing the refresh token on the client side is the only way to persist the session on something like a browser. However it has to been stored securely so there are two scenarios even here:
The refresh token get stored in the browser in something like the localStorage or the sessionStorage (less secure)
The refresh token is passed to the client using a HttpOnly cookie that are less reachable with Javascript.
Question
Assuming that we store the refresh token in an HttpOnly cookie I was wondering: does the endpoint /refresh_token, that returns a new JWT and a new refresh token, need to be authorized?
If the endpoint has to be authorized, I should have a valid JWT for validating my user without requesting username and password again. In a scenario where the user uses the web application in a browser, then he closes it, then after a while he returns to the web application (and the JWT has expired) this is not possible and requires the user to authenticate again.
If the endpoint is not authorized I cannot have, while validating the refresh token, a valid user instance to check the refresh token data against. So, the only thing that I can check is the validity of the refresh token with the store (or with JWT strategies). This solves the above-mentioned scenario but, is this safe enough?
Another scenario is that the endpoint accepts also expired JWTs, validates them and then it checks the refresh token.
How should the refresh token be validated for a secure implementation? What are the best practices about this?

Is this JWT based authentication method safe?

Trying to implement a secure authentication method with JWT for an API which will be consumed for many clients including web (Single Page App), desktop, mobile I've came up with this system:
Client calls /auth/login with username and password set
After verifying server returns two tokens an auth_token and a refresh_token
Auth token is short lived 15 minutes and is used on every following API call
Refresh token is long lived maybe a 12 hrs to a week BUT is signed with a secret key in the format user_pass + long_string
After the token expires a called to /auth/renew is called
The auth token is sent to check how long it's expired (no longer than an hour)
The refresh token is sent as well and is validated using the user's password
If refresh token isn't expired and the auth token isn't expired for a long time, a new auth token is sent back
If the user's password has changed, the refresh token is invalid and the user is required to re-authenticate after their existing short lived auth token has expired
While there is a small window for the auth token to be expired and still be valid, and there is calls to the database made; is this an overall secure way to authenticate using JWT and to handle password changes and token refresh?
Don't try to implement your own authentication infrastructure. Chances you'll get a secure implementation are minimal and now you'll have to maintain all that code also.
Better use a authorization server from a reputable origin, like Thinktecture IdentityServer or Azure Active Directory and use standard libraries and protocols.
Some problems I see with your proposal:
if you do not sign the access token, what prevents me from changing
the claims inside?
if you need the user's password to validate the refresh token, you must store it in a way that you can retrieve it in clear text. Passwords should only be stored as a salted hash preventing you from getting to the clear text.

oAuth 2.0 - Acting on behalf of the user

I'm new to oAUth2 and I'm trying to get a few things straight.
I understand the basic principles involved with oAuth2 but I am not sure how to implement it in my situation.
I am writing an app that acts on behalf of the user to automate a manual process and perform some tasks(update/request status...etc). The API we are connecting to uses oAuth2 to grant our application permission. We plan on having the user grant our application permission when they create a new account with us.
I understand that the user will request an authentication code that is provided to our application. Then our application will use the authentication code to generate an access token.
We would like to do this only once. Then act as the user to send and receive notifications without having to have the user to log into the service with their credentials.
I am not sure how to implement this without having to store the user credentials to get an auth code since the auth code and auth tokens expire. I'm guessing that this is a common scenario.
What would I need to do to get what I want accomplished?
You can get a new AccessToken using a RefreshToken, if this is provided by the Authorization Server.
If it's not provided I would contact the Api provider, you should never store a users credentials. In fact if the OAuth protocol is well implemented as a client you should never be able to even get the client credentials. When the user has to login you should redirect the user to the Authorization Server, there the user should login and then the authorization token should be redirected to your application by the Authorization Server.
See also this explanation on Refresh Tokens from the OAuth 2.0 spec:
Refresh tokens are credentials used to obtain access tokens. Refresh
tokens are issued to the client by the authorization server and are
used to obtain a new access token when the current access token
becomes invalid or expires, or to obtain additional access tokens
with identical or narrower scope (access tokens may have a shorter
lifetime and fewer permissions than authorized by the resource
owner). Issuing a refresh token is optional at the discretion of the
authorization server. If the authorization server issues a refresh
token, it is included when issuing an access token
Note
If you request a new AccessToken using your RefreshToken and the response includes a new RefreshToken you should overwrite your currently saved RefreshToken. With other words, you should always use the latest RefresthToken you received.