Java Web Token authentication mechanism

In the field of Web-based validation everywhere Token identity. In most Internet companies using the Web API in, token authentication is the best way to handle multi-user.

1. Comparison of several authentication mechanisms

1.1 Session Authentication

We know, http protocol itself is a stateless protocol, and this means that if the user provides a user name and password to our application for user authentication, then the next time request, the user should once again perform user authentication before OK, because, according to the http protocol, we can not know which user request is sent, so in order to make our application can identify which user request is issued, the information we can store a copy of the server user login, this login information It will be passed to the browser in response, telling save it as a cookie, so that next time the application is sent to our request, so that our application will be able to identify which user requests from, and this is the traditional session-based authentication.

1.2 Token Authentication

Similar to the http protocol is stateless token-based authentication mechanism, which does not require the server to retain the authentication information or session information of the user. This means that applications based on token authentication mechanism does not need to consider which server the user is logged in, which facilitated the application of the extension.
The process is this:

  1. User for username and password to the server request
  2. Server to verify the user's information
  3. The server sends to the user by verifying a token
  4. Client token memory, and each request included in this token value
  5. The server authentication token, and returns the data

1.3 Comparison of

Token mechanism relative to the Cookie mechanism what good is it?

  • Support cross-domain access : Cookie domain collapse is not allowed access, which is on the Token mechanism does not exist, provided that the user authentication information transmitted via HTTP headers transmission.
  • Stateless (also known as: scalable server line) : Token mechanism on the server to store session information is not required, because Token itself contains information about all logged-on user need only information stored in a cookie or a local state media clients.
  • Performance : a network round trip time (query session information through a database) than to do a HMACSHA256 calculated Token validation and much more time-consuming to resolve.
  • Based on standardized : Your API can be standardized JSON Web Token (JWT) This standard has multiple back-end database (.NET, Ruby, Java, Python , PHP) to adopt and support a number of companies (such as: Firebase, Google , Microsoft).

2. JWT

JSON Web Token (JWT) is a very lightweight specification. This specification allows us to use JWT deliver secure and reliable information between the user and the server.

Consisting of 2.1 JWT

A JWT is actually a string that consists of three parts, a head, a load signature.

Payload (Payload)

{ "iss": "Online JWT Builder", 
  "iat": 1416797419, 
  "exp": 1448333419, 
  "aud": "www.example.com", 
  "sub": "[email protected]", 
  "GivenName": "Johnny", 
  "Surname": "Rocket", 
  "Email": "[email protected]", 
  "Role": [ "Manager", "Project Administrator" ] 
}
  • iss: The JWT's issuer, whether to use is optional;
  • sub: The JWT is facing the user, whether to use is optional;
  • aud: JWT of the receiving side, whether to use is optional;
  • exp (expires): What time expired, here is a Unix timestamp, whether to use is optional;
  • iat (issued at): at what time of issuance (UNIX time), whether to use is optional;
    Others include:
  • nbf (Not Before): If the current time is before nbf in time, then the Token will not be accepted; usually leave some leeway, such as a few minutes; whether the use is optional;

The above objects JSON [Base64 encoded] can be obtained following string. We call it a string of JWT Payload (payload).

eyJpc3MiOiJKb2huIFd1IEpXVCIsImlhdCI6MTQ0MTU5MzUwMiwiZXhwIjoxNDQxNTk0NzIyLCJhdWQiOiJ3d3cuZXhhbXBsZS5jb20iLCJzdWIiOiJqcm9ja2V0QGV4YW1wbGUuY29tIiwiZnJvbV91c2VyIjoiQiIsInRhcmdldF91c2VyIjoiQSJ9

Header (Header)
JWT also need a head, the head is used to describe the basic information about the JWT, such as its type and algorithm used for the signature. This can also be expressed as a JSON object.

{
"typ": "JWT",
"alg": "HS256"
}

At the head of a signature algorithm is specified HS256 algorithm.
Of course, the head must also be BASE64 encoded encoded string as follows:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9

Signature (the Signature)
to the string above two encoding are connected together by a period (first head), it is formed:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmcm9tX3VzZXIiOiJCIiwidGFyZ2V0X3VzZXIiOiJBIn0

Finally, we will finish top stitching string encrypted with HS256 algorithm. In encryption, we also need to provide a key (secret). If we mystar as the key, then you can get the contents of our encryption:

rSWamyAYwuHCo7IFAgd1oRpSP7nzL7BF5t7ItqpKViM

Finally, these are also part of the signature stitching behind the string is signed, we get a complete JWT:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmcm9tX3VzZXIiOiJCIiwidGFyZ2V0X3VzZXIiOiJBIn0.rSWamyAYwuHCo7IFAgd1oRpSP7nzL7BF5t7ItqpKViM

We will take this request URL string JWT string:

https://your.awesome-app.com/make-friend/?jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmcm9tX3VzZXIiOiJCIiwidGFyZ2V0X3VzZXIiOiJBIn0.rSWamyAYwuHCo7IFAgd1oRpSP7nzL7BF5t7ItqpKViM

Note: secret is stored on the server side, the issue generated jwt also on the server side, secret is used to authenticate the issuance and jwt of jwt, so it is your server's private key, in any scenario should not be revealed to go. Once the client has learned the secret, it means that the client can be self-signed jwt up.

2.2 Approval Process

log in

Certification Request

3.Java achieve

Java support for JWT can consider using JJWT open source library; JJWT realized JWT, JWS, JWE and JWA RFC specification.

Generate Tokens

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import io.jsonwebtoken.*;
import java.util.Date;    
 
//Sample method to construct a JWT
private String createJWT(String id, String issuer, String subject, long ttlMillis) {
 
    //The JWT signature algorithm we will be using to sign the token
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
 
    long nowMillis = System.currentTimeMillis();
    Date now = new Date(nowMillis);
 
    //We will sign our JWT with our ApiKey secret
    byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(apiKey.getSecret());
    Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
 
    //Let's set the JWT Claims
    JwtBuilder builder = Jwts.builder().setId(id)
                                .setIssuedAt(now)
                                .setSubject(subject)
                                .setIssuer(issuer)
                                .signWith(signatureAlgorithm, signingKey);
 
    //if it has been specified, let's add the expiration
    if (ttlMillis >= 0) {
    long expMillis = nowMillis + ttlMillis;
        Date exp = new Date(expMillis);
        builder.setExpiration(exp);
    }
 
    //Builds the JWT and serializes it to a compact, URL-safe string
    return builder.compact();
}

Decode and Verify Tokens

import javax.xml.bind.DatatypeConverter;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.Claims;
 
//Sample method to validate and read the JWT
private void parseJWT(String jwt) {
 
    //This line will throw an exception if it is not a signed JWS (as expected)
    Claims claims = Jwts.parser()         
       .setSigningKey(DatatypeConverter.parseBase64Binary(apiKey.getSecret()))
       .parseClaimsJws(jwt).getBody();
    System.out.println("ID: " + claims.getId());
    System.out.println("Subject: " + claims.getSubject());
    System.out.println("Issuer: " + claims.getIssuer());
    System.out.println("Expiration: " + claims.getExpiration());
}

4. References

https://www.cnblogs.com/xiekeli/p/5607107.html

http://www.jianshu.com/p/576dbf44b2ae

https://stormpath.com/blog/jwt-java-create-verify

http://blog.leapoahead.com/2015/09/07/user-authentication-with-jwt/

pay

Guess you like

Origin www.cnblogs.com/coderzhw/p/11094295.html