access token usage in authentication - rest

I don't understand the point of having access token in authentication. Below is a paragraph of explanation I took but I still confused. Since every api call still go to the db look for the token, what's the different check for the username and password for every http request?
Instead of forcing clients to send username and password with every
request you can have a "get_access_token" function in your RESTful
service that takes the username and password and responds with a
token, which is some sort of cryptographic hash that is unique and has
some expiration date associated with it. These tokens are stored in
the database with each user. Then the client sends the access token in
subsequent requests. The access token will then be validated against
the database instead of the username and password.

Using the access token limits the amount of time the username and password are being used and sent across the wire.
How many times do you want your username and password, SSN, or other sensitive data do you want being stored and transmitted? Do you want that on every request?

First of all, access tokens are typically validated by checking the digital signature, which does not require the receiving service to talk to the issuing server. The client gets an access token once and uses it until it expires.
But even if the token had to be checked against the database on every call (when using reference tokens for example), tokens are still preferred over sending username and password on each call. They remove the need for the client to keep the password in memory (or elsewhere), where it can easily be stolen.

(1) Access token is less sensitive than your password. Access tokens typically expire after a short time (this is a requirement in the Oauth threat model), whereas passwords tends to be long term. If somebody grabs your access token, there is limited damage they can do. If they grab your password, then there is a lot of damage that they can do. Especially if you use the same or related passwords on multiple sites.
(2) If the server implemented password verification securely, then they should be using a slow function like PBKDF2, bcrypt, or scrypt to validate your passwords. These functions are designed to be slow so that if somebody gets access to the database, they will not be able to reverse many passwords: see Our password hashing has no clothes. Given that password checking is supposed to be slow, we don't want to be doing it often! Validation of access tokens is much quicker however.
(3) The system that grants you access to a resource ("resource provider") might not be the same as the system that checks your identity ("identity provider"). For example, many websites including StackOverflow allow you go login with your gmail account. In this case, Google is the identity provider and StackOverflow is the resource provider. Would you really want to provide your gmail password to StackOverflow? I hope not.

Related

Is it a bad practice to store JWT tokens in database?

To implement a logout function, i stored JWT tokens in database.
When the user logs out, i just delete the token from the database and if there is no token in the database, i fire an unauthorized response.
Is this a bad practice or a necessity to implement this function?
I also want to implement an ip confirmation so the JWT is only valid if it comes from the ip address, so i will just add an ip column next to JWT column and also check ip...
Even if my JWT tokens are cracked, since i store them in database, an attacker cannot login my system. The system looks like to me more powerfull this way.
What is your experience and knowledge about this?

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.

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.

Best practices for token authentication in web apps?

I want to make a simple REST web app, where the user interact with the objects through links in an email. The links have a token that can be used to authenticate a user without a username and password, like the ones that are usually used to reset a password.
What are the best practices for such a login-less, token-based authentication system?
I am by no means a security expert.. but some of the points which come to mind are -
Lifetime - The token should expire after a set period of time. Indefinite access using the token certainly doesn't make sense.
Replay attacks - The mechanism should prevent replay attacks.. which means the token should be valid for not only a set period of time, but also fixed number of calls.. Ideally exactly 1. If this number is not exactly 1, then it opens another can of worms..
Unless, its a feature :( For example, by design, the user is expected to share link with others, and anyone with the link should be able to access the resource in question.
Authorization - Granularity of the access granted by the token. Is it black and white.. or is the token also associated with a fixed set of rights. For example - token X was issued for Read-Only access, vs token Y was issued, for same resource with R/W access.
Administration - User / Admin should be able to see and verify any currently active and issued tokens, and associated information (permissions granted / affected resource etc), and explicitly revoke them, if necessary.
Secure Communication - You should consider security of the medium through which the url with token will be sent to the user. i.e. in your scenario, do the users receive emails over secure channel (TLS / SSL)? Should the email itself be protected with DRM?
Man in the Middle / Leaks - Similarly, even though you are providing the url in email, and the user is not logging on using user name and password over SSL, the resource should still be accessed using the url with token over SSL. This will prevent any capturing of the tokens from url, by a man in the middle. You would also need to be very careful about when the users browser may use this url in places you didn't expect..
I can vaguely recall reading about a popular site being affected by their urls being used as Refer Url, when displaying ads on their website.. which means, the advertisers site would probably get the url with the token as Refer.
Generation - Choice of algorithm to generate the token - May seem pretty obvious, but the token should be extremely obscure and near impossible to guess or brute force. The tokens should never be reused and the algorithm should avoid collisions.
Server Side Security - The tokens should probably be treated with same security as you would secure users id and password. If your user database gets hacked, hackers should not get the users passwords and other sensitive information.. Similarly, if your user / resource / token database gets hacked, despite the expiration on the tokens, hackers should not be able to access the resources as users for x hours.
Point is, when the tokens are stored on server side, they should themselves be secured / encrypted.
On the same lines.. just like its bad practice to log information like passwords in log file (specially plain text), You'd also have to consider any place these urls may get logged (plain text) on your server.. For example web server logs. If only super admins should have access to user's database, then they should also be the only ones to be able to see these token.. Not your web server admin and not any hackers parsing the log file after the hack.
Auditing - If there will be a need for auditing, you'd need some mechanism in place to prove that while the user didn't log on to the system, they are indeed the ones who performed the action / operation in question. Would you want to track the ip address and other information along with the request which would help such auditing?
Consent - Do your users even consent to the use of such alternate means of authentication and authorization? Should this be an optional / opt in feature?
EDIT: I found a link to the referrer url problem I was recalling. Although it was in context of user information.
I agree to 10 points of Vikas however from security perspective I have to tell you few points that you must be careful.
I will try to keep as simple as possible. And here I simplify the technical stuff to your special case.
Firstly tokens are used to prevent Cross Site Request Forgery attacks (XSRF). Keep that in your mind. If there is a web platfrom without unique tokens on the forms then any attacker can force the user to make malicious requests.
If you simply try to authenticate the user with a token, this is pretty wrong. Because there must be no simple authentication process and you can not rely on token.
Here is how the login system works in official security documentations, im writing as I remember:
Identification: you have to identify the user firstly, that is generally done with username. YOu will know that there is a user exist in your system.
Authentication: Let's say you have already identified that user A want to login. So you mast authenticate the user A with something that you know and user A know. We call it password simply :) You cannot by pass this step with plain text methods. Passwords are generally encrypted in your db and also through all communication with secure certicates, check ssl.
Authorization: okay you made the authentication somehow, the user has a right to get Authorization. Let's say if the admin type user is logged in, he has differen rigts and if the normal user is logged in then she has regular rights.
Session control: finally you have to control the session with a secure way. Here generally in web applciations people use access tokens for all requests to be sure that the authorized user is aware of the request. As a platform owner you are responsible to secure everything until the session ends. If you don't satisfy the users with your security, then probably your platf is not going to survive longer.
Tokens have different lifetime to expire and different access rights.
Now let's look at what facebok like companies do with mobile aplications. For the mobile app they generate a unique access token which is alway alive. One shortcoming here is, if any attacker steal the mobile token generally she can do anything in the account anytime :) Anyway here our point is how they verify the users with those tokens; firstly the token is unique for that device. (Actually not exactly unique or not dependent on hardware, because if you clearly steal the necessary files from the device then you can use it on another phone). So with this unique access token which is generated with users password at their initial login on mobile app, they can login always automatically with that. And this method is a little similar to what you want to do. However pay attention that they don't authenticate the users with links or email code.
Verification is not an authentication, don't forget that. By sending e-mail you can verify the users if the emailed code is unique and valid for only 30 sec or 1 minute. I hope you got the point.
Here I suggest you to check single sign on across multiple domains, which is really interesting.
Single Sign On across multiple domains
Let's say you are logged in to google.com and then you visit the youtube.com Opps the youtube is already logged in? Yea, cool right, but exist for long time. They can authenticate users accross domains which use different cookies with a little and secure trick. You will read on the link.
If your service is not really confidential and if you want to make your users happy with easy login system. Here is two of my solutions which I love :)
1-) Ask users their email address: just directly send 4-6 digit code as e-mail. Ask user the enter/click on that. There will be no password at all, only unique code on each login.
2-) Let's say you need to verify the user with a stronger way than email. Then mobile phone :) Here trick is; you will not send the verification code to user, but they will send what you tell them to you.
Ask to user to send a SMS with a unique CODE to XXXXXX your number :) Connect your mobile operator with your web service and check whether the code is sent to you by the user :)
There is always a trade-off between security and simplicity, and also with complexity. You have to find the balance.
Don't try to make it simple if your security is going away.
Don't try to make it complex if it'll seem more secure.
Hope those informationn help you.

Restricting REST API results based on the user

I am building a messaging application using BackboneJS which naturally persists using a REST interface.
The issue I'm having is that I don't know how to restrict what data a user can pull back from the API. For instance a call to /messages would, at the moment, return messages for ALL users. I would like that resource to only return messages belonging to the current user.
Searching online seems to indicate that oAuth2 is the best way to solve this issue but all the tutorials talk about been redirected to another place to confirm access and retrieve an access token.
Given that my users will have already logged into the message application and that the REST API is actually part of the same application I don't like the idea of asking the users to confirm that my own app can access my own API.
Is there a better way?
oAuth2 is probably your best bet -- you definitely don't want to roll your own security. However, the flavor of oAuth2 you are thinking of is probably not what you want.
oAuth2 has four different flavors, known as authorization grant types:
Authorization code: This is the type you are thinking about. It is often called three-legged oAuth, because there are three actors in the token granting process (app, resource owner, and user). The app asks the user whether it is ok for the resource owner to give specific type(s) of access to the resource. It is a rather complex process that allows the validation of user credentials without allowing the app access to them. This is not necessary in your case, since you are both the app and resource owner.
Client credentials: This is a method for authorizing a client application with the server. It does not use user credentials at all. If you completely trust your client application (all client applications) to correctly protect user data and not expose other user's data to the user using the app, or you are providing only non-user data via the API (for example, map data or catalog data), you might be able to use this fairly simple type of oAuth2. However, if you want to be vigilant in protecting user data (and not allow apps to get to the data without the user providing credentials), you might not use this one.
Resource owner password credentials: The username and password of the user is passed via https to your backend server, which authenticates and authorizes access by providing an access token. The access token can then be passed with each call, and it remains valid for accessing the backend until a configurable time period has elapsed. This means that someone intercepting the token could only use it successfully for a limited amount of time (some number of minutes, generally). The interceptor would not know the username and password of the user. In addition, you can supply the app with a refresh token, which can be used to get a new access token once it has expired (until the refresh token expires -- usually with a significantly longer expiration date). Since the credentials are not passed across the wire often (and must only be passed encrypted), this is often the best solution for protecting user credentials and not requiring the user to pass them in often (good user experience). Implementation is much simpler than for the authorization code grant type.
Implicit: This is the least secure method -- no credentials are validated server side at all. This is usually used for client side scripting languages where credentials cannot be stored safely. If you are worried about security at all, avoid this type if possible.
So, check out OAuth 2.0, and look for the resource owner password credentials grant type.