Revoking Bearer Token and Refresh Token - ServiceStack - servicestack

I want to enforce a single user session feature for my Angular app because my customers share a single account with their coworkers.
The issue currently, with my implementation. is revoking a valid token stored a client's local storage, particularly a valid Refresh token.
The scenario is:
User 1 logs in with valid username and password, the bearer token will expire in an hour, the refresh token will expire in two weeks
User 2, uses the same username and password two hours later. User 2 is prompted that they are logged in on another device and asked the question of they would like to expire that session and start a new session.
User 2 says yes and the now User 1's session in invalid.
The problem is that User 1 still has a valid Refresh token.
I have no way revoke this refresh token. My Auth API will accept is valid and I will not know whether it is User 1 or User 2's refresh token.
Do I need to start storing refresh token values in my database to resolve this issue? I also thought I could use a different JwtAuthKeyBase64 for User1 and User2, as a way to invalidate User1's token but this doesn't seem like a good way to be using the ServiceStack JwtAuthProvider.

The JWT RefreshToken is used to contact the Auth Server to fetch a new JWT Bearer Token. It will only return a BearerToken if the User still has Access so you can lock the User Account by populating UserAuth.LockedDate which will prevent the user from retrieving a new JWT Bearer Token.
If you want more custom validation you can implement IUserSessionSource and throw an Exception in GetUserSession() to return an Error Response instead of the JWT Bearer Token.

Related

JWT tokens flow - log out case

I am creating node.js/express project. Authentication is done based on JWT. Details:
When user log in, in response there is access token (validation: 15 minutes) and refresh token (validation: 24 hours). In payload of each token there are user's most neccessary data and unique identifier which is used to make these token kind of pairs. These tokens are "bond". On logout this identifier is put on blacklist - for more read below.
In each request I check access token: a) if token is real token (not faked one), b) if it is expired or c) token contains in its payload an unique identifier which was put on the blacklist. In case access token expired check out no 3 below.
When access token expired, there sie /refreshToken endpoint where user can refresh both access token and refresh tokens. In case unique identifier is in the blacklist token will not be refreshed and user should re-authenticate.
And finally, there is /logout endpoint where user pass access token in request. And again, if unique identifier is in blacklist there is error in response. However if access token is valid, unique identifier is put on the blacklist and user is logged out.
What I need to mention here is I do not store refresh tokens in database as in many other solutions. All is based on unique identifier.
Basically, my goal was to be sure that when user logged out (access token in request), no one will use refresh token to regain access token. In this solution both tokens should be useless.
What do you think of this flow. What do you think of unique identifier which pairs both access and refresh token?
Would you improve that in any way?

Cookie Security Issue

I'm creating a authentication route where user can login and u know the rest.
So after login im creating a refresh token (using JWT) which valid for 7 days, and with help of that refresh token i create access token (valid for 15 min) for logging in a users.
So to access a refresh token in frontend im storing this to cookie i.e refreshToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6I..." (whatever that string is). The problem is if any one access this refresh token and store it manually he can login as that user, until that jwt token expires. Im not storing Access token in cookie.
So What could be the solution for this, im thinking of storing refresh_token in user DB and update as user login.
Any suggestions will really appreciated :)

Make jwt token expired after one of the user's property has changed

is it possible to make jwt token expired after one of the user's property has changed ( for example - activated: false or role: [ADMIN] )? Or maybe there is another way to solve this problem?
Typically a JWT expires only when the expiry date for that token passes. But this doesn't mean that a JWT cannot expire logically for other reasons. One example would be that your Node application receives a request with a valid JWT, but the token belongs to a user whose account was recently deactivated. The workflow might look something like this:
Your Node app receives the JWT
It decrypts the JWT, and extracts the username
Then it queries a user table in your database to check the status of the account
Having discovered that the account is not active, your Node app redirects to the login page with an error message
It is generally up to you to determine how to proceed with a JWT. The JWT just protects the token from being manipulated by the user.

Can we use JWT for Session management?

After introducing JWT in my own application. I am facing some issues, might be I do it in wrong way. Please Suggest me the best way of implementation.
Technology Stack : (MERN) MongoDB Expressjs React Node.
After successfully login , I am creating a new JWT token by adding "user-id" in to it and return back to UI layer. At UI end I am storing that token in session storage. This token I am using for all further requests to the server. Before going to the controller I am checking Token in middleware for validtaion by using JWT verify. if successfully verified then next() else return an error with an invalid token.
Issue accurs now :
Register with USER 1
Login with USER 1
After successfully login copy Token from session storage.
Then Logout USER 1
Register with USER 2
Login with USER 2
Paste in session storage Token of USER 1 into USER 2
After refreshing a page USER 1 dashboard again instead of USER 2.
Any help or suggestions for following two points:
How should I manage user Session by JWT?
How should I manage API Authentication by JWT?
You should either not store tokens in the browser session or at least delete it when logging out. The token contains all information about the user as well as the signature, that verifies the validity of the token. If you copy & store it, it is still valid. Logging out the user doesn't invalidate the token.
You should add an expiry to the token to make it valid only a short time, but you need to refresh it then in intervals before it gets invalid. The normal way to do this is to use a refresh token which has a longer interval and keeps the user from logging in again and again.
When the user logs out, you should stop re-issuing access tokens from the refresh token.
See https://jwt.io/introduction/ for further information about JWT.

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