How to make a valid access token invalid - rest

In restful application, for some reqirements,e.g. On client side,for the same user can using only one access token at the same time and user can get new access token via login successfully.if logined twice,the user will got two different access token say it's access token A and B.In the backend,when user still use token A to talk with server, it should be invalid and the latter B should be valid!How to implement this without using cache framework or db?
Additionally in the backend, i don't want store any access token, the access token contains simple user info and timestamp etc, which is a string encrypted with aes and encoded with Base64.

Unfortunately, you won't be able to do what you want without persisting the tokens.
I answered a question related to token based authentication before. Maybe you can get some inspiration from there.
Different types of tokens
Basically, a token can be opaque (which reveals no details other than the value itself, like a random string) or can be self-contained (like JSON Web Token).
Random String: A token can be issued by generating a random string and persisting it to a database with an expiration date and with a user identifier associated to it.
JSON Web Token (JWT): Defined by the RFC 7519, it's a standard method for representing claims securely between two parties. JWT is a self-contained token and enables you to store a user identifier, an expiration date and whatever you want (but don't store passwords on it) in a payload, which is a JSON encoded as Base64. The payload can be read by the client and the integrity of the token can be easily checked by verifying its signature on the server. You won't need to persist JWT tokens if you don't need to track them. Althought, by persisting the tokens, you will have the possibility of invalidating and revoking the access of them. To find some great resources to work with JWT, have a look at http://jwt.io.
Persisting tokens
There are many databases where you can persist your tokens. Depending on your requirements, you can explore different solutions such as relational databases, key-value stores or document stores.
Just remember to remove old tokens in order to prevent your database from growing indefinitely ;-)

The access token must be send in every request in Authorization header. For every user you store his access token. So access token arrives, you check its value and find which user it is. If you do not find access token, user is not authorized.
So basically when you generate new token, you replace the old access token for given user, when old access token comes you are not able to recognize it (it is not stored anywhere), therefore it is invalided.

Related

is it a good idea to put expired tokens to blacklist table?

To begin with this is how my current auth flow looks
User logs in
User gets a refresh_token assigned and stored in the database (long lived 7d)
Client receives an accestoken (Short lived, 2h), and stores it as a cookie. Client also receives the userId AES encrypted, and stores
it as a cookie.
As far as the access token is not expired, the user keeps using the token to navigate the website
The token expires
The expired access token gets send to a refresh endpoint, so is the userID (Aes encrypted) both currently stored in out cookies.
The server decrypts the userId and retrieves the refreshtoken that corresponds to the user by selecting the refresh token from the database using out userId.
Now we have in the server our refreshtoken and accestoken, so we refresh the token, and send back the new accesstoken. We also generate a new refreshtoken and overwrite our old refreshtoken in the database with the new one.
My question is basically related to that last step. Since those refresh tokens are still technically valid, since they have a long expiration time. Can I create a table in my database named "blacklisted_tokens" or something like that, and store there the values of the token? And then right before generating a new access token it should prior to that check if that refresh token is or isnt in that database, meaning that it will be blacklisted.
This is the authflow diagram
My question is basically related to that last step. Since those
refresh tokens are still technically valid, since they have a long
expiration time. Can I create a table in my database named
"blacklisted_tokens" or something like that, and store there the
values of the token? And then right before generating a new access
token it should prior to that check if that refresh token is or isnt
in that database, meaning that it will be blacklisted.
it's not recommended to do that as because, probability of generating 2 same token is low and adding NOT necessary additional processes to your back-end is not a good idea and has performance issue in large scale Token re-generation(a lot of users).
And also, Tokens are along with an identity(id) in which reduces security risks.
if i were you, i would just re-write new-token to old-token.
The most important type of cyber attack which threaten Tokens is The Sniffing attack and by doing below steps actually the probability of this attack goes almost to zero:
SSL certificate
Expiring Token and re-generation
Salty requests
Salt
In cryptography, a salt is random data that is used as an additional
input to a one-way function that hashes data, a password or
passphrase. Salts are used to safeguard passwords in storage.

What is the difference between a JWT token and a Refresh token?

I'm trying to get my head around refresh tokens and how they work with JWT, so I can use it without auth0 API service.
Why refresh token format is different from JWT?
refresh tokens are just simple tokens store in the db?
How is the flow to use a refresh token to get a JWT token?
Thanks!
UPDATE
As #Florent Morselli suggested. The fundamental question of this post is wrong and confusing. Since JWT and refresh tokens are not really concepts that can be related. A better question can be:
What is the difference between a JWT Token and an opaque token?
What is the difference between a Access Token and a Refresh Token?
I'm not changing the question in the title, since somebody might be looking wrongly for the same thing and it will lead them to this post.
Token can be of two types:
Tokens by Reference
Tokens by Value
With the first type, the tokens are opaque strings (often random strings) that refer to a database index where the values associated to the tokens are stored.
With the second type, the tokens contain the values. To avoid alteration they are digitally signed or hashed. As they also may contain sensitive data, they can be encrypted.
JSON Web Token is a suite of specifications (mainly RFC7515 to RFC7520) that introduces a new format for the second type.
Why Refresh tokens issued by oauth0 are of the first type and not JWT (second type)?
The main benefit of the tokens by value is that they can be stateless i.e. you don't need any kind of database.
This is really helpful when tokens are sent several times to a server as they drastically reduce database calls and thus reduce the response time.
The drawback is that you cannot revoke them. Or if you add a revocation system, then you have to manage and call a database.
Therefore , tokens by value should have a very limited lifetime which is not compatible with refresh tokens.
Refresh token are used in Code flow or Hybrid flow as per OpenID Spec See Image below
Reference: https://openid.net/specs/openid-connect-core-1_0.html#CodeFlowSteps
Why refresh token format is different from JWT?
The format of Refresh token is also as per spec from OpenID
Reference: https://openid.net/specs/openid-connect-core-1_0.html#CodeFlowSteps
refresh tokens are just simple tokens store in the db?
Refresh tokens would be generated from your IDP(Identity Provider dynamically).
How is the flow to use a refresh token to get a JWT token?
Once you have the refresh token as shown in previous step, you can make a request to Token Endpoint with Refresh token to get Access Token
Access token

Confusion around Access, ID, and Refresh JWT authentication

I've been developing my first REST API to serve as the back-end for a mobile application. I'm pulling info from different resources, and am a little confused when it comes to the token implementation (I'm using JWT).
The access token is used to ensure that the requester has access to the resource that is being called. My understanding is that I will then encode the user details in the ID Token, such that the relevant information can be returned. The refresh token is used as a security mechanism, to keep the user authenticated after the short-lived ID and access tokens expire.
The access token seems a little redundant, and maybe it is an interchangeable term for ID token? Can I just remove that part from my authentication scheme?
In the proposed scheme access and ID tokens are used interchangeably and do not provide any value over the other. All information provided in the access token can be stored in the ID token, or vice versa. The entire authentication scheme will then simply consist of an access token (containing both info on access permissions, and user info), and a refresh token (ensuring that users don't need to login again every t minutes).

Why can i easily decode auth0 id_token on jwt.io?

Okay, i'm developing an Angular 2 app. I've added auth0 authentication, but to me it handles sessions very insecurely. The jwt token is not encrypted and saved inside localStorage. The claims are visible for anyone, they can easily be decoded and revealed. Not to mention, Web Storage itself isn't a secure place.
I'm opting for JWTs because later i want to transform this web app to desktop app with electron and so i cannot use cookie-sessions. My users will have additional information such as roles, which i don't want to look up in db on every request, that's why i would like to store them in jwt. It makes sense to encrypt the data, but auth0 doesn't seem to provide that function.
If claims like roles are stored in localStorage unprotected, what's stopping me to go to firefox console and change the token, e.g. make myself an admin?
If claims like roles are stored in localStorage unprotected, what's stopping me to go to firefox console and change the token, e.g. make myself an admin?
Because JWT is signed, so any alteration to the content or the signature will be detected during validation
The digital signature, the third part of a JWT token like this hhhhhh.ppppppp.ssssss is created using server private key, and is the way you can verify the identity of the issuer of the token and also that it has not been altered
If you want to hide the payload, the JWT specification allows use encryption (see Json Web Encryption-JWE at RFC). If auth0 does not support it, you have a lot of libraries listed in jwt.io
JWT token has two parts: explicit (codet by base64 algorithm) - with payload data like for example exp time or user Id and role etc. and implicit - hash key which guarantee with extremely high probability that any part of explicit data was not change after token was created (by server using it's private key). So in Local/Session storage you can store this explicit part. The full token should be store in httpOnly cookies - then you will be protected against XSS attack (where hacker want to stole you token).
So you can read and change jwt token payload from firefox, but you will be unable to generate implicit hash - and server will reject your token.
So the answer to title question is: because Auth0 id_token is JWT token :)

JWT for stateless API, but session control for security

I really want to use JWT for API access, to keep it stateless. But at the same time I need to have strong security recourse to deny tokens that are yet to expire.
For more sensitive user information APIs I can rely on forcing a fresh login, comparing the IP address, etc. But I still want to be able to revoke a users token if needed. I don't mind paying the overhead price.
What I imagined would be to have each user create their own secret key based on their password, and store it in the session. I don't mind trading the overhead for an easier way to deal with stolen tokens. This way a simple password reset should invalidate old tokens.
Acknowledging the trade off, does this method make sense? Are there better ways to go about this?
You should create a "blacklist" on your server. If a token needs to be revoked, place it in the blacklist and set it to expire from the list when the token expires. For every authentication attempt, you will verify that the incoming JWT is not in the blacklist. Redis can make this quite easy.
Alternatively, consider a third-party service such as Stormpath. Disclaimer: I work for Stormpath. We have an Oauth2 api that let's you issue access + refresh tokens (for a password grant flow). We handle revocation for you, so long as you don't mind the overhead of the REST call to verify the state of the token. Please see Using Stormpath for OAuth 2.0 and Access/Refresh Token Management. We have easy support for this in our Express-Stormpath .library
well, i just had the same kind of implementation. add hashed password to token, and when client returns the token, during validation, check if user's password has been changed in db, if user's hashed pass is not the same as the one you put in token, reject the token. In this way, you don't need to keep any info about user and/or token on the server.
I don't like the idea of white/black listing tokens, so I ended up using the users hashed password + another random key as their token's secret key:
+---------------+------------------------------------+-----------+
| email | password | key |
+---------------+------------------------------------+-----------+
| user#mail.com | asfsifj2fij4f4f4f8d9dfhs.8f8fhsd8h | r4nd0Mk3Y |
+---------------+------------------------------------+-----------+
I then keep a cache in memory of users id=>password+key to verify each users token. This way tokens can be discarded when: 1) user resets password; 2) application changes the user key.
This almost defeats the purpose of JWT's, but I need this layer of security for my use case.
JSON Web Token
JSON Web Token (JWT) is defined by the RFC 7519.
It's a standard method for representing claims securely between two parties. JWT is a self-contained token and enables you to store a user identifier, an expiration date and whatever you want (but don't store passwords) in a payload, which is a JSON encoded as Base64.
The payload can be read by the client and the integrity of the token can be easily checked by verifying its signature on the server.
Tracking your tokens
You won't need to persist JWT tokens if you don't need to track them.
Althought, by persisting the tokens, you will have the possibility of invalidating and revoking the access of them. To keep the track of JWT tokens, instead of persisting the whole token, you could persist the token identifier (the jti claim) and some metadata (the user you issued the token for, the expiration date, etc) if you need.
Your application can provide some functionality to revoke the tokens, but always consider revoking the tokens when the users change their password.
When persisting tokens, always consider removing the old ones in order to prevent your database from growing indefinitely.
Additional information
When sending sensitive data over the wire, your best friend is HTTPS and it protects your application against the man-in-the-middle attack.
To find some great resources to work with JWT, have a look at http://jwt.io.