I love the java series --- [micro JWT implement authentication service]

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.

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

Head (Header)

Header 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. We BASE64 encoding http://base64.xpcha.com/ , after a string of coded as follows:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9

Tips: Base64 is based on 64 printable characters to represent binary data representation. Since the sixth power of 2 equal to 64, so every six bits as a unit, corresponding to a printable character. There are three bytes of 24 bits, corresponding to four Base64 units, i.e. 3 bytes need four printable characters to represent. JDK provides a very convenient  BASE64Encoder  and  Base64Decoder , using them can be very convenient been completed based on the encoding and decoding BASE64

Load (playload)

Load local storage is valid information. The name refers specifically to such goods carried on the aircraft, these effective information consists of three parts

(1) standard registration statement (recommended, but not mandatory to use)

iss: jwt issuer 
sub: jwt are oriented user
aud: jwt receiving party
exp: jwt expiration time, the expiration time must be greater than the issue of time
nbf: what time before defined, which are unavailable jwt.
IAT : jwt the issue of time
jti: jwt unique identity, it is mainly used as a one-time token.

(2) a public statement

Public declarations can add any information, general information about the user to add the necessary information or other business needs, but is not recommended for sensitive information to add, in part because the client can decrypt.

(3) private statement

Private statement is a statement providers and consumers as common definition, is generally not recommended to store sensitive information, because base64 is decrypted symmetric, meaning that some of the information may be classified as plaintext.

This refers to the custom of the claim. Such as for example in front of the structure and name belong admin from a given claim. claim the difference between the provisions of these standards that claim with JWT: claim JWT specified, the recipient after JWT JWT get, know how to claim these standards to verify (do not know whether verification); and private claims will not verification, unless explicitly tell the recipient to verify the claim and the rules of the job.

Define a payload:

{"sub":"1234567890","name":"John Doe","admin":true}

Base64 then be encrypted to obtain the second portion of Jwt.

eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9

Visa (signature)

The third part is a jwt visa information, this visa information consists of three parts:

header (after the base64)

payload (after the base64)

secret

and using the payload header of this part needs after base64 base64 encryption encrypted connection string composed of salt and then encrypted by the secret encryption header compositions declared, and the third portion constitutes the jwt.

TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

Connection with these three parts into a complete string, constitutes the final jwt.:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

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.

JJWT issuance and verification token

JJWT JWT is a provider of end-to-create and verify Java library. Forever free and open source (Apache License, version 2.0), JJWT is easy to use and understand. It is designed with a sleek interface building for the center, hides most of its complexity.

The official document:

https://github.com/jwtk/jjwt

JWT's Quick Start:

 

1 Create token

 

(1) add a dependency in the pom.xml new project:

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.9.0</version>
</dependency>

(2) create a test class, as follows

public  class TestJWT {
     // This is our key, encryption and decryption require the use of 
    Private  Final  static String keywords = "itcast" ; 
    @Test 
    public  void testCreate () {
         Long currentTimeMillis = System.currentTimeMillis ();
         // create jwt 
        Builder = JwtBuilder Jwts.builder () 
                            .setId (UUID.randomUUID (). toString ())   // set a unique number 
                            .setSubject ( "rookie siege lion") // set the theme may be JSON data 
                            .setIssuedAt ( new new a Date ( ))   //Set the date of issue 
                            . SetExpiration ( new new a Date (currentTimeMillis + 50000)) // set the expiration time
                 
. The Claim ( "the Roles", "administrator") // Custom claim, set a role
                 .signWith (SignatureAlgorithm.HS256, keywords); / / set the signature algorithm using HS256 and set SecretKey (string)
// construct and return a string 
        System.out.println (builder.compact ()); 

    }

Print run results:

eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI4ODgiLCJzdWIiOiLlsI_nmb0iLCJpYXQiOjE1NTc5MDQxODF9.ThecMfgYjtoys3JX7dpx3hu6pUm0piZ0tXXreFU_u3Y

Run again, you will find the results of each run is not the same, because our load included time.

2 parsing token

We have just created the token, the operation is performed by a server in a web application and then sent to the client, the client the next time you send a request to the server need to bring this token (this is like holding a ticket the same) that the server received the token should parse out information (such as user id) token, return the appropriate result based on the information query the database.

 

@Test
    public void testParser(){

        String compactJwt = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI5ODEwNjZkNS1kOTkwLTQ1NWQtOWJhNy0zNGYyZjlhNjA2ODYiLCJzdWIiOiLpu5HpqaznqIvluo_lkZgiLCJpYXQiOjE1NjU2ODM4MDcsImV4cCI6MTU2NTY4Mzg1NX0.efXeiB1EcXPjRO-ZkE7Xm2gvhY7EUd-uLiUFFZkJ0YE";
        Claims claims = Jwts.parser().setSigningKey(keywords).parseClaimsJws(compactJwt).getBody();
        System.out.println(claims);
    }

Print run:

{Jti = 888, sub = white, iat = 1557904181}

Try the signature key or token tampering, you will find the error will be running, so parsing token is verified token. The current time exceeds the expiration time, it will error.

 

4 custom claims

 

We just examples simply store the id and two information subject, if you want to store more information (such as roles) can define a custom claims.

 

Create a test class, and set the test method:

 

Create a token: a code written on top, the claim is marked red.

 

 

Guess you like

Origin www.cnblogs.com/hujunwei/p/11346770.html