I love the java series --- JWT [token]

JWT token advantages:

1, jwt based json, very easy to resolve. 
2, you can customize in the token rich content, easy to expand.
3, by an asymmetric encryption algorithm and digital signature technology, the JWT prevent tampering, safety.
4, resource service uses JWT not depend certification services to complete the authorization.

Disadvantages:

    1, JWT token longer storage accounted for a larger space.  

Token structure:

JWT token consists of three parts, each part separated by the use of an intermediate, such as (.): Xxxxx.yyyyy.zzzzz

Header

The head includes a token type (i.e. JWT) and the hash algorithm used (e.g., HMAC SHA256 or RSA)

An example follows:

Below is part of the contents of Header

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

The top of the content using encoding Base64Url, to give the first portion is a string token JWT.

Payload

The second part is the load, the content is also a json object that is a valid place to store information that can be stored ready-field jwt offer, such as: iss (issuer), exp (expiration timestamp), sub (for users) etc., can also be custom fields.

This section is not recommended to store sensitive information, because this section can decode restore the original content.

Finally, the second portion of the load Base64Url encoding used, to give a second portion of the string is JWT token.

one example:

{
"sub": "1234567890",
"name": "456",
"admin": true
}

Signature

The third part is the signature, this section jwt to prevent content from being tampered.

This section uses the first two parts base64url encoded using the encoded dot (.) Connected to form a string, header signature algorithm declared the last used for signing.

one example:

HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret)

base64UrlEncode (header): the first portion jwt token.

base64UrlEncode (payload): jwt second portion of the token.

secret: the key used to sign.

manual:

1. generate a key (to ensure that your computer can run a normal Java environment, including public and private keys here)

 

 

 

keytool -genkeypair -alias changgou -keyalg RSA -keypass changgou -keystore changgou.jks -storepass changgou 

Queries certificate information:

keytool -list -keystore changgou.jks

 

 

 2. Export public key from the key

openssl encryption and decryption is a kit, where the use openssl to export the public key information.

Install openssl (all the way to the next default), Download: http://slproweb.com/products/Win32OpenSSL.html

Installation Win64OpenSSL-1_1_1b.exe in the data directory

Openssl configuration of the path environment variable,

 

 

 

cmd into the directory where the file changgou.jks execute the following command: The white part is the public key

keytool -list -rfc --keystore changgou.jks | openssl x509 -inform pem -pubkey

 

 

 The top copy of the public key to a text file public.key, must remember to manually merge into one line, it can be put under the authorization and authentication need to implement the project resource file directory, which projects need to put where.

3. Based on the secret key generation token jwt

Code Baidu cloud download link:

Links: https://pan.baidu.com/s/1gZZT0hglb3XPIKIgJrYTPg
extraction code: zrv6
copy the contents of this open Baidu network disk phone App, the operation more convenient oh

3.1 Import Certification Services

1) The courseware changgou_user_authengineering introduced into the project, as shown below:

 

 

 2) Start eureka, then start the authentication service

Create a test class 3.2 Certification Service

public  class CreateJwtTest { 

    / ** * 
     * Create a token test 
     * / 
    @Test 
    public  void testCreateToken () {
         // certificate file path 
        String key_location = "changgou.jks" ;
         // secret key store password 
        String Key_password = "changgou" ;
         // keys password 
        String keypwd = "changgou" ;
         // keys alias 
        String alias = "changgou" ; 

        // accessed certification path 
        a ClassPathResource Resource = new new a ClassPathResource (key_location); 

        // create a secret key factory
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(resource,key_password.toCharArray());

        //读取秘钥对(公钥、私钥)
        KeyPair keyPair = keyStoreKeyFactory.getKeyPair(alias,keypwd.toCharArray());

        //获取私钥
        RSAPrivateKey rsaPrivate = (RSAPrivateKey) keyPair.getPrivate();

        //定义Payload
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("id", "1");
        tokenMap.put("name", "itheima");
        tokenMap.put("roles", "ROLE_VIP,ROLE_USER");

        generate Jwt token//
        Jwt jwt = JwtHelper.encode(JSON.toJSONString(tokenMap), new RsaSigner(rsaPrivate));

        //取出令牌
        String encoded = jwt.getEncoded();
        System.out.println(encoded);
    }
}

4 based on public key token parsing jwt

After creating the token above, we may parse the token JWT, where parsing need to use a public key, we can copy public.key previously generated public key token string variables out with storage, and then decrypted by the public key.

Create Test class changgou-user-oauth com.changgou.token.ParseJwtTest achieve parse token verification data, as follows:

public  class ParseJwtTest { 

    / ** * 
     * verification token 
     * / 
    @Test 
    public  void testParseToken () {
         // the token 
        String token = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlcyI6IlJPTEVfVklQLFJPTEVfVVNFUiIsIm5hbWUiOiJpdGhlaW1hIiwiaWQiOiIxIn0.IR9Qu9ZqYZ2gU2qgAziyT38UhEeL4Oi69ko-dzC_P9- Vjz40hwZDqxl8wZ-W2WAw1eWGIHV1EYDjg0-eilogJZ5UikyWw1bewXCpvlM-ZRtYQQqHFTlfDiVcFetyTayaskwa-x_BVS4pTWAskiaIKbKR4KcME2E5o1rEek-3YPkqAiZ6WP1UOmpaCJDaaFSdninqG0gzSCuGvLuG40x0Ngpfk7mPOecsIi5cbJElpdYUsCr9oXc53ROyfvYpHjzV7c2D5eIZu3leUPXRvvVAPJFEcSBiisxUSEeiGpmuQhaFZd1g -yJ1WQrixFvehMeLX2XU6W1nlL5ARTpQf_Jjiw " ; 

        // public
        String publickey = "-----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvFsEiaLvij9C1Mz+oyAmt47whAaRkRu/8kePM+X8760UGU0RMwGti6Z9y3LQ0RvK6I0brXmbGB/RsN38PVnhcP8ZfxGUH26kX0RK+tlrxcrG+HkPYOH4XPAL8Q1lu1n9x3tLcIPxq8ZZtuIyKYEmoLKyMsvTviG5flTpDprT25unWgE4md1kthRWXOnfWHATVY7Y/r4obiOL1mS5bEa/iNKotQNnvIAKtjBM4RlIDWMa6dmz+lHtLtqDD2LF1qwoiSIHI75LQZ/CNYaHCfZSxtOydpNKq8eb1/PGiLNolD4La2zf0/1dlcr5mkesV570NxRmU1tFm8Zd3MZlZmyv9QIDAQAB-----END PUBLIC KEY-----";

        //校验Jwt
        Jwt jwt = JwtHelper.decodeAndVerify(token, new RsaVerifier(publickey));

        //获取Jwt原始内容
        String claims = jwt.getClaims();
        System.out.println(claims);
        //jwt令牌
        String encoded = jwt.getEncoded();
        System.out.println(encoded);
    }
}

 

 

 

 

 

Guess you like

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