OAuth 2.0. No session? (stateless)

后端 未结 2 1590
猫巷女王i
猫巷女王i 2021-02-04 04:58

I\'m going to implement OAuth 2.0 and REST API with it

to grant different permissions per users and also to scale well.

To scal

2条回答
  •  抹茶落季
    2021-02-04 05:46

    A more recent innovation is JWT - JSON Web Token.

    Here is a link to the spec: JWT - JSON Web Token

    JWT is a method of using Hashed tokens using a Hashing method such as HMAC which stands for a Hash-based Message Authentication Code. Because the token is hashed using a secret key, the server can determine if the token has been tampered with.

    Here is an example method to create a Hashed token 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 ensure it was not tampered with:

    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: Stateless Authentication

提交回复
热议问题