JWT知识

2023-12-17 14:55:48

JWT概念

JWT组成

Java实现JWT

Header

String getHeader() {
    String header = "{\"alg\":\"HS256\",\"typ\":\"JWT\"}";
    String encodeBase64URLSafeString = Base64.encodeBase64URLSafeString(header.getBytes(StandardCharsets.UTF_8));
    System.out.println(encodeBase64URLSafeString);
}

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9

PayLoad

void getPayLoad(){
    String payload = "{\"sub\":\"7isi\",\"id\":\"1001\",\"role\":\"admin\"}";
    String encodeBase64URLSafeString = Base64.encodeBase64URLSafeString(payload.getBytes(StandardCharsets.UTF_8));
    System.out.println(encodeBase64URLSafeString);
}

eyJzdWIiOiI3aXNpIiwiaWQiOiIxMDAxIiwicm9sZSI6ImFkbWluIn0

Signature

@Test
void generatesignature() throws NoSuchAlgorithmException, InvalidKeyException {
    String secret = UUID.randomUUID().toString().replaceAll("-", "");
    String data = getHeader() +"." + getPayLoad();

    Mac mac = Mac.getInstance("HmacSHA256");
    SecretKeySpec spec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8),"HmacSHA256");
    mac.init(spec);
    byte[] bytes = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
    String res = Base64.encodeBase64URLSafeString(bytes);
    
    String jwt = data + "." + res;
    System.out.println(jwt);
}

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI3aXNpIiwiaWQiOiIxMDAxIiwicm9sZSI6ImFkbWluIn0.vpwacNY4fLdQzF7iSDyGLnYMqbgBoWRVLNG7Ail15Ss

验证签名值

计算出来和原来的对比,我们的secreat是早就准备好的

Web中使用JWT

JJWT

依赖

<dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-api</artifactId>
            <version>0.11.5</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-impl</artifactId>
            <version>0.11.5</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-jackson</artifactId>
            <version>0.11.5</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15on</artifactId>
            <version>1.70</version>
            <scope>runtime</scope>
        </dependency>

例子

生成jws

RSA算法的支持

JWT安全密钥实现

以下是jwt,没有签名,文档错误

自定义key

压缩

获取jwt的数据

add是往后添加

文章来源:https://blog.csdn.net/qq_56127002/article/details/135038117
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。