初次体验JWT

我按教程简单的体验了一下JWT,我没有走完整的JWT流程,只走了一下加密部分,我的代码如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

public class JWTUtils {

    private static final SystemProperties systemProperties = new SystemProperties();

    public static String signature(Header header, Payload payLoad) throws Exception {

        switch (systemProperties.getEncryptionAlgorithm()) {
            case AES:
                /*
                    我疑惑的点:我看示意图,是需要对header和payload各自进行base64加密的
                    然后对加密结果用点号链接起来,然后再用

                 */
                return AESUtils.encrypt(
                        String.format("%s.%s",
                                Base64.getEncoder().encodeToString(JSON.toJSONString(header).getBytes(StandardCharsets.UTF_8)),
                                Base64.getEncoder().encodeToString(JSON.toJSONString(header).getBytes(StandardCharsets.UTF_8))),
                        systemProperties.getPrivateKey());
            case SM3:
            case SM4:
            default:
                throw new RuntimeException("未准备的加密方式");
        }
    }

    public static String token(Header header, Payload payLoad) throws Exception {
        return String.format("%s.%s.%s",
                Base64.getEncoder().encodeToString(JSON.toJSONString(header).getBytes(StandardCharsets.UTF_8)),
                Base64.getEncoder().encodeToString(JSON.toJSONString(payLoad).getBytes(StandardCharsets.UTF_8)),
                signature(header, payLoad));
    }

    public static void main(String[] args) throws Exception {

        Header header = Header.builder()
                .alg("HS256")
                .typ("JWT")
                .build();

        Payload payload = Payload.builder()
                .id("100")
                .name("zhangsan")
                .phone("13579246810")
                .expire("200")
                .build();

        System.out.println(token(header, payload));
    }

}

参考资料

  1. 简单代码实现JWT(json web token)完成SSO单点登录

  2. jwt.io