接口自动化框架后端(2)-jwt登陆验证

2023-05-15 23:14:23 浏览数 (1)

1、后端打算用jwt来做登陆和权限验证,首先添加依赖

代码语言:javascript复制
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>4.3.0</version>
        </dependency>

2、利用密钥生成token,这里写一个测试类测试一下:

代码语言:javascript复制
public static final String SECRET = "bMc4zT87kP5x4nFPD3oj";

    @Test
    void contextLoads() {
    }

    @Test
    void createToken() {
        HashMap<String, Object> headers = new HashMap<>();
        Calendar expires = Calendar.getInstance();
        expires.add(Calendar.SECOND,1800);
        String jwtToken = JWT.create()
                .withHeader(headers)
                .withClaim("id", 106)
                .withClaim("username", "Jack")
                .withExpiresAt(expires.getTime())
                .sign(Algorithm.HMAC256(SECRET));
        System.out.println(jwtToken);
    }

生成的token生成的token

3、再写一个测试方法,解析token,记得verify方法传入刚才生成的token

代码语言:javascript复制
  @Test
    void analysisToken() {
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT decoded = jwtVerifier.verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MTA2LCJleHAiOjE2ODQxNjUyMjAsInVzZXJuYW1lIjoiSmFjayJ9.6k_7Ha2EPE5iMhVEZVE0XAj2bOGdxz6vKAjwJgt-_fQ");

        System.out.println(decoded.getClaim("id").asInt());
        System.out.println(decoded.getClaim("username").asString());
        System.out.println(decoded.getExpiresAt());
        System.out.println(decoded.getToken());
    }

这里看到token的内容成功的被解析出来了

token解析token解析

0 人点赞