5分钟详解JWT

本文介绍了如何在SpringBoot项目中集成JWT,并展示了创建和验证JWT令牌的步骤。通过添加spring-security-jwt依赖,创建测试类,对JWT的生成和解码过程进行了详细解释,包括头部信息、有效载荷和签名的组成。最后,提到了JWT在OAuth2授权中的应用场景,演示了如何在请求头中携带JWT进行授权验证。
摘要由CSDN通过智能技术生成

 1、创建一个maven工程,引入jwt的springboot依赖

            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-jwt</artifactId>
                <version>1.0.10.RELEASE</version>
            </dependency>

2、创建一个测试类

public class JWTTest {
    String accessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9" +
            ".eyJhdWQiOlsicmVzMSJdLCJ1c2VyX25hbWUiOiJhZG1pbiIsInNjb3BlIjpbIlJPTEVfQURNSU4iLCJST0xFX1VTRVIiLCJST0xFX0FQSSJdLCJleHAiOjE2MjAzODQ5NjIsImF1dGhvcml0aWVzIjpbIlJPTEVfYWRtaW4iLCJ0ZXN0Il0sImp0aSI6ImY2MTk4MjBhLWIxOTItNDI4Yy05ZmFlLTg0YWMzMTI0NGZlMCIsImNsaWVudF9pZCI6InNwcmluZ2Nsb3Vkc2VjdXJpdHkifQ.lSpV6_0nFylzhdwTlqX_U4SkkcCRPn3tn5yAh12wyzU";

    String content ="{\"aud\":[\"res1\"],\"user_name\":\"admin\",\"scope\":[\"ROLE_ADMIN\",\"ROLE_USER\"," +
            "\"ROLE_API\"],\"exp\":1620384962,\"authorities\":[\"ROLE_admin\",\"test\"]," +
            "\"jti\":\"f619820a-b192-428c-9fae-84ac31244fe0\",\"client_id\":\"springcloudsecurity\"}";

    /**
     * 签名密钥
     */
    private final String signingKey = "jwtSigningKey";
    /**
     * 签名算法
     */
    private final Signer signer = new MacSigner(signingKey);
    /**
     * 认证密钥
     */
    private final String verifierKey = signingKey;
    /**
     * 认证算法
     */
    private final SignatureVerifier signatureVerifier = new MacSigner(verifierKey);

    @Test
    public void encode(){
        final Jwt encode = JwtHelper.encode(content,signer);
        System.out.println(encode.getEncoded());
        final String encodeJwt = encode.toString();
        System.out.println(encodeJwt);
        final Jwt decode = JwtHelper.decodeAndVerify(encode.getEncoded(), signatureVerifier);
        System.out.println(decode.toString());
        assert  encodeJwt.equals(decode.toString());
    }

    
    @Test
    public void decode(){
        final Jwt decode = JwtHelper.decode(accessToken);
        System.out.println(decode);
    }

}

3、运行一下结果:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsicmVzMSJdLCJ1c2VyX25hbWUiOiJhZG1pbiIsInNjb3BlIjpbIlJPTEVfQURNSU4iLCJST0xFX1VTRVIiLCJST0xFX0FQSSJdLCJleHAiOjE2MjAzODQ5NjIsImF1dGhvcml0aWVzIjpbIlJPTEVfYWRtaW4iLCJ0ZXN0Il0sImp0aSI6ImY2MTk4MjBhLWIxOTItNDI4Yy05ZmFlLTg0YWMzMTI0NGZlMCIsImNsaWVudF9pZCI6InNwcmluZ2Nsb3Vkc2VjdXJpdHkifQ.lSpV6_0nFylzhdwTlqX_U4SkkcCRPn3tn5yAh12wyzU
{"alg":"HS256","typ":"JWT"} {"aud":["res1"],"user_name":"admin","scope":["ROLE_ADMIN","ROLE_USER","ROLE_API"],"exp":1620384962,"authorities":["ROLE_admin","test"],"jti":"f619820a-b192-428c-9fae-84ac31244fe0","client_id":"springcloudsecurity"} [32 crypto bytes]
{"alg":"HS256","typ":"JWT"} {"aud":["res1"],"user_name":"admin","scope":["ROLE_ADMIN","ROLE_USER","ROLE_API"],"exp":1620384962,"authorities":["ROLE_admin","test"],"jti":"f619820a-b192-428c-9fae-84ac31244fe0","client_id":"springcloudsecurity"} [32 crypto bytes]

4、详解

jwt = 头部信息.有效信息.签名

jwt= eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsicmVzMSJdLCJ1c2VyX25hbWUiOiJhZG1pbiIsInNjb3BlIjpbIlJPTEVfQURNSU4iLCJST0xFX1VTRVIiLCJST0xFX0FQSSJdLCJleHAiOjE2MjAzODQ5NjIsImF1dGhvcml0aWVzIjpbIlJPTEVfYWRtaW4iLCJ0ZXN0Il0sImp0aSI6ImY2MTk4MjBhLWIxOTItNDI4Yy05ZmFlLTg0YWMzMTI0NGZlMCIsImNsaWVudF9pZCI6InNwcmluZ2Nsb3Vkc2VjdXJpdHkifQ.lSpV6_0nFylzhdwTlqX_U4SkkcCRPn3tn5yAh12wyzU

  • 头部信息,base64加密

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9

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

jwt的头部承载两部分信息:

  1. 声明类型,这里是JWT
  2. 声明加密的算法 通常直接使用 HMACSHA256,也就是测试类中MacSigner使用的默认算法
  • 有效信息,base64加密

eyJhdWQiOlsicmVzMSJdLCJ1c2VyX25hbWUiOiJhZG1pbiIsInNjb3BlIjpbIlJPTEVfQURNSU4iLCJST0xFX1VTRVIiLCJST0xFX0FQSSJdLCJleHAiOjE2MjAzODQ5NjIsImF1dGhvcml0aWVzIjpbIlJPTEVfYWRtaW4iLCJ0ZXN0Il0sImp0aSI6ImY2MTk4MjBhLWIxOTItNDI4Yy05ZmFlLTg0YWMzMTI0NGZlMCIsImNsaWVudF9pZCI6InNwcmluZ2Nsb3Vkc2VjdXJpdHkifQ
包括:标注声明(选填)+公共声明+私有声明

  标准中注册的声明(都是选填)

{
	"aud": ["res1"],
	"exp": 1620384962,
	"jti": "f619820a-b192-428c-9fae-84ac31244fe0",
}
  • iss: jwt签发者
  • sub: jwt所面向的用户
  • aud: 接收jwt的一方
  • exp: jwt的过期时间,这个过期时间必须要大于签发时间
  • nbf: 定义在什么时间之前,该jwt都是不可用的.
  • iat: jwt的签发时间
  • jti: jwt的唯一身份标识,主要用来作为一次性token,从而回避重放攻击。

  公共的声明

  私有的声明

{    
    "user_name": "admin",
    "scope": ["ROLE_ADMIN", "ROLE_USER", "ROLE_API"],
    "authorities": ["ROLE_admin", "test"],
    "client_id": "springcloudsecurity"
}
  • 签名:HMACSHA256(头部信息 +"."+有效信息,secret)

lSpV6_0nFylzhdwTlqX_U4SkkcCRPn3tn5yAh12wyzU

5、在springboot oauth2中的应用

curl --location --request GET 'http://localhost:8080/' \
--header 'Authorization: Bearer eyJhdWQiOlsicmVzMSJdLCJ1c2VyX25hbWUiOiJhZG1pbiIsInNjb3BlIjpbIlJPTEVfQURNSU4iLCJST0xFX1VTRVIiLCJST0xFX0FQSSJdLCJleHAiOjE2MjAzODQ5NjIsImF1dGhvcml0aWVzIjpbIlJPTEVfYWRtaW4iLCJ0ZXN0Il0sImp0aSI6ImY2MTk4MjBhLWIxOTItNDI4Yy05ZmFlLTg0YWMzMTI0NGZlMCIsImNsaWVudF9pZCI6InNwcmluZ2Nsb3Vkc2VjdXJpdHkifQ'

在Header中加入Authorization头,写入jwt即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

宇哥哦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值