Clear tokens on end session - identityserver3

Is there possibility to automatically clear tokens for a given client when user performs end session?
Or i have to manually clear them by calling token revocation endpoint (yes I'm working with reference tokens for this scenario)?

You can implement the SignOutAsync method in your user service. From there you know who the user is (the subject id) and can then delete the tokens using the token handle store.

Related

What are best practices using AWS Cognito to authenticate a REST API

I'm building a REST API and using AWS Cognito's user pools for authentication. I've got a "get_token" endpoint that returns the JWT access and refresh tokens to the user, which they use to authenticate access to the other REST endpoints provided by the API.
The access token has an expiration timeout. If the user of my API is an application program, what are the best practices for the application to handle when the access token expires? Does the application have to remember the username/password and re-authenticate to continue? Is using the refresh token to get a new access token and use that going forward the best approach?
Is there any documentation, suggestions anyone can point out that might help me out?
Cognito provides 3 types of tokens, id, access and refresh tokens when you login. The way this usually works is that you send either of the first two (depends on whether you want to be sending user payload information to your backend) to your backend via an Authorization header and verify the token there.
Your id and access tokens usually have a shorter expiration time compared to the refresh token. What you should do is, when the id (or access) token expire, you should use the refresh token to generate a new id (or access) token. When the refresh token expires that means that you can no longer generate new id/access tokens from it. In this case, the user (or app) must login again.

What is the point of refresh token in jwt?

Please don't mark as duplicate I came through a lot of questions like this but still I didn't get the point of refresh token. Some of the reason they said are:
If an attacker gets the access token it will expiry soon
But where I am confused is if the attacker was able to get the access token why they wouldn't be able to get the refresh token (both of them needed to access token by JS to sent request so they needed to store in local storage)
If the attacker gets the refresh token we can block it in server.
But we can also block the access token in server right. (with DB)
Note I am not talking about OAuth refresh token, because as per the answers I read,
The idea of refresh tokens is that if an access token is compromised,
because it is short-lived, the attacker has a limited window in which
to abuse it.
Refresh tokens, if compromised, are useless because the attacker
requires the client id and secret in addition to the refresh token in
order to gain an access token.
So it makes sense here but what about JWT?
Typically the access token gets sent with every request, and to your API.
Typically a refresh token only gets sent once, immediately expires after use and only goes to your authentication server. All these measures generally reduce risk.
JWT and OAuth2 can be used together, and it's highly recommended to use OAuth2 instead of trying to write something from scratch.
I talk a bit more about the pitfalls in my article: https://evertpot.com/jwt-is-a-bad-default/
The refresh token allows the client to make a call and ask for a new access token. For setups where the access token does have a certain expiry, the refresh token will typically have an expiry which is later than the access token itself. Here is a typical workflow using access and refresh tokens:
The client authenticates to the server via 1FA or 2FA
The server responds with an access token having an expiry in 5 minutes, along with a refresh token which expires a minute later
The client then uses the access token as needed.
When authentication fails using the current access token, under the hood the client will take the refresh token and hit the server to get a new access token. We then go to step #2 above and recycle.
Note that for certain instances, the refresh token is not needed. One example would be sites like Stack Overflow, which uses token which never expire. Another example would be certain high security sites such as banking sites. In these cases, the site might force you to reauthorize via 1FA/2FA in order to keep the session going.
One way in which an update of the authentication token can be carried out through another and without exposing it to client applications (avoiding its use in a malicious way), is to store it in a cache system such as REDIS and in the When the request token has expired, check in storage if the user has a refresh token that allows him to regenerate the authentication. This could be implemented within the same middleware that validates the token that accompanies the request or in an endpoint intended for this purpose.

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.

Does I understand access and refresh token technique for authentication correctly?

After doing some research in using JWT with Access Token and Refresh Token for authentication. I understand this in this way.
After login, return to user Access Token and Refresh Token (using same technique JWT for both).
Saving Refresh Token in Database (one User can have multiple Refresh Tokens for multiple devices).
Whenever user sends a request with invalid Access Token, check Refresh Token and call another api to get new Access Token (doing this in client side). After that, call api to get data again with new Access Token.
If Refresh Token is invalid, deleting its record in database and user must to login again to get new Refresh Token.
Does I understand Access and Refresh Token technique correctly? Please give me some advices. Thank in advance.
Of the 4 steps you listed, some look more or less correct while others do not. I will begin this answer by giving the premise for why refresh tokens were created and what is their main purpose.
Using the JWT pattern with only access tokens, there is a potential usability problem when the JWT token expires. Consider as an example a banking website. When a user logs in, he receives a JWT token with a certain expiry (typically stored under the exp key in the claims section of the token). If the token is given say a 5 minute expiry, then from a usability point of view, it means that the website would have to force the user to manually login every 5 minutes. Obviously, this is not the best user experience, because it means that a user who happens to be in the middle of some business process when the token expires might lose all that work. This is where refresh tokens step in to alleviate this problem.
Using the JWT pattern with refresh tokens means that the user receives both an access and a refresh token. A typical workflow here might be:
After login, return to user Access Token and Refresh Token (using same technique JWT for both). The receiver notes when the access token is set to expire (say 15 minutes).
As the expiry of the access token approaches (e.g. 10 minutes), the UI will send the refresh token to the backend to obtain a new access token (and refresh token). This could be done explicitly, e.g. on a website which displays a popup asking if the user wants to continue. Or it could be done in stealth mode, with a REST call being made under the hood to get the new access token.
For the edge case where the refresh token cannot be used to obtain a new access token, then the very next user action which requires authentication would fail. In this case, the user would have to redirected to the login page. But, as this case should generally be rare, it does not disqualify the refresh token pattern.
I would also point out that storing the access/refresh tokens in the database largely defeats the purpose of the JWT pattern. One major reason for using JWT is that it pushes the user session state out of the application and onto the user. By storing tokens in your database, you are totally making your user sessions very stateful, which has all sorts of potential drawbacks. Consider using the suggested workflow above to avoid doing this.
The way I see it, your refresh token needs to be stored and associated with the device and the user.
Example:
User Logs In in Device A
Call Login endpoint
Validate user is valid
If valid, generate a refresh token associated with the userid & device
id
store required data to your table or storage engine (user_sessions..etc)
user_id | device_id | refresh_token | expires_at
Return the payload with access_token, refresh_token , access_token_expires_at, refresh_token_expires_at
Front-end, store the payload
when consuming a resource, check the following
If refresh_token_expires_at > now then logs them out , show your session is timeout (or you can have a never expired refresh_token.. ex. refresh_token_expires_at can be 0)
if access_token_expires_at > now then call refresh token endpoint along with your payload.
on the refresh endpoint, validate the call and check the refresh token against the data stored.
if refresh token is valid for this user+device, generate a new access_token
return the access_token and its expires_at
If the refresh token is INvalid , return invalid
front end will log the user out.
** in any case, if a refresh token was compromised, it will be only for that particular device/user. A user can then deactivate or remove the device from their list. This action will invalidate the refresh_token on their next refresh call.

Looking for some advice on front end/backend user authentication

I'm running a mock expressjs server in the back, and ember (ember-simple-auth) on the front with the ember-simple-auth-token addon. I'm using JWT tokens. I'm trying to decide whats the best way to send my user information. Usually when the user submits their credentials I create a new token, store a copy of it in the database (I'm using mongodb), send it to the frontend and then use the token to fetch information user information. I have a /auth/token (which authenticates and sends the token, makes a copy and stores it in the database) & /current_user route which gets called on the initial login, which uses the token and fetches the user info.
Is it better to simply send the user info in the initial payload of the token over having a separate route? Should I be storing a copy in the database in order to do a comparison and retrieve user information?
Also what are the advantages of a token refresh?
you are using Jwt-Auth for authentication.
-According to my knowledge after sending the user credentials u will respond with the token if credentials are correct otherwise send error.
-why are you saving the token in db ?.
you will send token to client (stateless). If client requests for data then we need to check for token. if it validates then return proper response otherwise return token error.
-why you need token refresh?
for security purpose. After response every time change the token.
TTL your token will be valid for some time (say 60 mins). after that it will be invalid.
This is how JWT works.