Token based authentication in REST APIs

2019-03-22 00:47发布

I trying to implement a token based authentication approach:

  1. Every successful login creates new token.

  2. If user selects "keep me logged in" or the user is using a mobile device, the token is persisted in a Redis database without an expiration date. Otherwise, the token will expire in 20 minutes.

  3. Once user is authenticated, the token is checked from each subsequent request in my Redis database.

I'm wondering how I can identify devices. In case of mobile devices, I can use a device identifier. But how can I identify a browser?

Example: The user logs in using Chrome and selects "keep me logged in". A token is generated and persisted with the browser name in Redis. If the user logs in from Firefox, saves the token and "Firefox" in the database. I save the token in Redis whereas token is created on successful authentication. Is it fine to persist only the token and the browser where the token is being used? Or do I need to persist the IP as well?

Additional question: How to avoid attackers to steal the token from a cookie?

2条回答
别忘想泡老子
2楼-- · 2019-03-22 01:13

How token-based authentication works

In a few words, an authentication scheme based on tokens follow these steps:

  1. The client sends their credentials (username and password) to the server.
  2. The server authenticates the credentials and generates a token.
  3. The server stores the previously generated token in some storage along with the user identifier and an expiration date.
  4. The server sends the generated token to the client.
  5. In every request, the client sends the token to the server.
  6. The server, in each request, extracts the token from the incoming request. With the token, the server looks up the user details to perform authentication and authorization.
    1. If the token is valid, the server accepts the request.
    2. If the token is invalid, the server refuses the request.
  7. The server can provide an endpoint to refresh tokens.

How to send credentials to the server

In a REST applications, each request from client to server must contain all the necessary information to be understood by the server. With it, you are not depending on any session context stored on the server and you do not break the stateless constraint of the REST architecture defined by Roy T. Fielding in his dissertation:

5.1.3 Stateless

[...] each request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client. [...]

When accessing protected resources that require authentication, each request must contain all necessary data to be properly authenticated/authorized. It means the authentication will be performed for each request.

Have a look at this quote from the RFC 7235 regarding considerations for new authentication schemes:

5.1.2. Considerations for New Authentication Schemes

There are certain aspects of the HTTP Authentication Framework that put constraints on how new authentication schemes can work:

  • HTTP authentication is presumed to be stateless: all of the information necessary to authenticate a request MUST be provided in the request, rather than be dependent on the server remembering prior requests. [...]

And authentication data (credentials) should belong to the standard HTTP Authorization header. From the RFC 7235:

4.2. Authorization

The Authorization header field allows a user agent to authenticate itself with an origin server -- usually, but not necessarily, after receiving a 401 (Unauthorized) response. Its value consists of credentials containing the authentication information of the user agent for the realm of the resource being requested.

Authorization = credentials

[...]

Please note that the name of this HTTP header is unfortunate because it carries authentication data instead of authorization. Anyways, this is the standard header for sending credentials.

When performing a token based authentication, tokens are your credentials. In this approach, your hard credentials (username and password) are exchanged for a token that is sent in each request.

What a token looks like

An authentication token is a piece of data generated by the server which identifies a user. Basically, tokens 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) 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 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. To find some great resources to work with JWT, have a look at http://jwt.io.

Tip: Always consider removing old tokens in order to prevent your database from growing indefinitely.

How to accept a token

You should never accept expired tokens or tokens which were not issued by your application. If you are using JWT, you must check the token signature.

Please note, once you issue a token and give it to your client, you have no control over what the client will do with the token. No control. Seriously.

It's a common practice to check the User-Agent header field to tell which browser is being used to access your API. However, it's worth mention that HTTP headers can be easily spoofed and you should never trust your client. Browsers don't have unique identifier, but you can get a good level of fingerprinting if you want.

I don't know about your security requirements, but you always can try the following in your server to enhance the security of your API:

  • Check which browser the user was using when the token was issued. If the browser is different in the following requests, just refuse the token.
  • Get the client remote address (that is, the client IP address) when the token was issued and use a third party API to lookup the client location. If the following requests comes an address from other country, for example, refuse the token. To lookup the location by IP address, you can try free APIs such as MaxMind GeoLite2 or IPInfoDB. Mind that hitting a third party API for each request your API receives is not a good idea and can cause a severe damage to the performance. But you can minimize the impact with a cache, by storing the client remote address and its location. There are a few cache engines available nowadays. To mention a few: Guava, Infinispan, Ehcache and Spring.

When sending sensitive data over the wire, your best friend is HTTPS and it protects your application against the man-in-the-middle attack.

By the way, have I mentioned you should never trust your client?

查看更多
Deceive 欺骗
3楼-- · 2019-03-22 01:17

Once server is receives the request from the client, it contains the User-Agent. This attribute will help us to identify the client.

Please refer this link: How do I detect what browser is used to access my site?

查看更多
登录 后发表回答