OAuth 2.0. No session? (Without citizenship)

I am going to implement OAuth 2.0 and REST API

provide different permissions for each user, and also scale well.

To scale well, statelessness is easier because there are

NO file, database, memory based session with it.


Below I understand how OAuth 2.

  • The OAuth server provides an access token to the user.
  • The user's access token is stored in a cookie.
  • When a user accesses the REST API, the user sends it using an access token.
  • The server receives a request with an access token.
  • The server finds out if the access token is valid and the user has permission to execute the request.
  • Do or reject based on user privileges.

Therefore, I do not need to worry about session storage. Correctly?

+8
rest oauth session stateless
source share
2 answers

What you are describing here is OAuth 2 Implicit grant flow . OAuth 2 also includes three other streams, but it seems your ressource owner (user) is initiating requests using Javascript on the browser side (you were talking about cookies), this is the stream you should use.

On the client side, OAuth requires that you save access_token for access to protected resources (and refresh_token if you expire access_token ).

+8
source share

A more recent innovation is the JWT-JSON Web Token.

Here is the link to the specification: JWT - JSON Web Token

JWT is a method of using Hashed tokens using a Hashing method such as HMAC, which stands for Hash-based message authentication code. Since the token is hashed using a secret key, the server can determine if the token has been changed.

Here is an example of a method for creating a Hashed marker for JWT:

  public String createTokenForUser(User user) { byte[] userBytes = toJSON(user); byte[] hash = createHmac(userBytes); final StringBuilder sb = new StringBuilder(170); sb.append(toBase64(userBytes)); sb.append(SEPARATOR); sb.append(toBase64(hash)); return sb.toString(); } 

Here is an example of decoding a token to make sure it has not been changed:

 public User parseUserFromToken(String token) { final String[] parts = token.split(SEPARATOR_SPLITTER); if (parts.length == 2 && parts[0].length() > 0 && parts[1].length() > 0) { try { final byte[] userBytes = fromBase64(parts[0]); final byte[] hash = fromBase64(parts[1]); boolean validHash = Arrays.equals(createHmac(userBytes), hash); if (validHash) { final User user = fromJSON(userBytes); if (new Date().getTime() < user.getExpires()) { return user; } } } catch (IllegalArgumentException e) { //log tampering attempt here } } return null; } 

Here is an article with a more complete example: Idle Authentication

+4
source share

All Articles