当前位置:网站首页>Simple use of JWT

Simple use of JWT

2022-07-06 06:53:00 sky~

 rely on 
   <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.18.2</version>
        </dependency>
 Use 
package com.sky;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Calendar;
import java.util.HashMap;

@SpringBootTest
class DemoApplicationTests {
    

    @Test
    void contextLoads() {
    
        HashMap<String,Object> map = new HashMap<>(); // The head is  HashMap  type 
        // Set expiration time 
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND,1000);// Set expiration time to  1000  second  Calendar.SECOND  second  Calendar.DATE  God ...
        // form JWT
        JWTCreator.Builder builder= JWT.create();
        builder.withHeader(map) // head  header  Can not add , There will be one by default MAP
                .withClaim("userId",1) //payload ,  Multiple groups can be used  , If there are more than one , You can deposit it first MAP aggregate , Last foreach Traversal read 
                .withClaim("userName","test") //payload
                .withExpiresAt(instance.getTime());  // Set token expiration time 
        String token =builder.sign(Algorithm.HMAC256("[email protected]##$$%@!")); // Signature 
        System.out.println(token); // Get the generated Token
    }
    @Test
    public void test(){
    
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("[email protected]##$$%@!")).build(); // Based on the signature JWT Verify the object 
        // Verify the generated above Token,  Here, if you only verify whether it is legal , You can no longer obtain the following information after execution if it is illegal , There will be anomalies 
        DecodedJWT verify = jwtVerifier.verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyTmFtZSI6InRlc3QiLCJleHAiOjE2NDQ3MTc5NDYsInVzZXJJZCI6MX0.r8JiKm10KU7IMfe17JU5-2N_cEwdUQhwl2l84zP7oO4");
        // Get some verified information 
        System.out.println(verify.getExpiresAt()); // Get expiration time 
        System.out.println(verify.getClaim("userId").asInt());// obtain payload  Note that the type corresponds to the above one by one 
        System.out.println(verify.getClaim("userName").asString());// obtain payload
    }
}

原网站

版权声明
本文为[sky~]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131953291762.html