【SpringSecurityOauth2整合JWT】

目录

JJWT demo

pom文件

创建Token

解析Token

SpringSecurityOauth2整合JWT

JwtToken配置类

授权服务器配置类 

​编辑 扩展JWT中存储的内容

 解析JWT中内容


SpringSecurityOauth2请参考【SpringSecurityOauth2】_angel277的博客-CSDN博客SpringSecurityOauth2授权码模式demo密码模式demohttps://blog.csdn.net/qq_42341853/article/details/125003700

JJWT demo

pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>jjwtdemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>jjwtdemo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--JWT依赖-->
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

创建Token


    /**
     * 创建Token(失效时间)
     */
    @Test
    public void testCreateTokenHasExp(){
        //当前系统时间
        long now=System.currentTimeMillis();
        //过期时间,一分钟
        long exp=now+60*1000;

        //创建JwtBuilder对象
        JwtBuilder jwtBuilder=Jwts.builder()
                //声明的标识{"jti":"8888"}
                .setId("8888")
                //主体,用户{"sub":"Rose"}
                .setSubject("Rose")
                //创建日期{"ita":"xxx"}
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256,"xxxx")
                //设置过期时间
                .setExpiration(new Date(exp));
        //获取jwt的token
        String token=jwtBuilder.compact();
        System.out.println(token);
        System.out.println("===========解密打印============");
        String[] split=token.split("\\.");
        System.out.println(Base64Codec.BASE64.decodeToString(split[0]));
        System.out.println(Base64Codec.BASE64.decodeToString(split[1]));
        System.out.println(Base64Codec.BASE64.decodeToString(split[2]));

    }
    /**
     * 创建Token(自定义申明)
     */
    @Test
    public void testCreateTokenByClaims(){
        //创建JwtBuilder对象
        JwtBuilder jwtBuilder=Jwts.builder()
                //声明的标识{"jti":"8888"}
                .setId("8888")
                //主体,用户{"sub":"Rose"}
                .setSubject("Rose")
                //创建日期{"ita":"xxx"}
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256,"xxxx")
                //自定义申明
                .claim("roles","admin")
                //直接传入map
                //.addClaims(map)
                .claim("logo","xxx.jpg");
        //获取jwt的token
        String token=jwtBuilder.compact();
        System.out.println(token);
        System.out.println("===========解密打印============");
        String[] split=token.split("\\.");
        System.out.println(Base64Codec.BASE64.decodeToString(split[0]));
        System.out.println(Base64Codec.BASE64.decodeToString(split[1]));
        System.out.println(Base64Codec.BASE64.decodeToString(split[2]));

    }

解析Token

    /**
     * 解析token(失效时间)
     */
    @Test
    public void testParseTokenHasExp(){
        String token="eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI4ODg4Iiwic3ViIjoiUm9zZSIsImlhdCI6MTY1MzAxODc4MywiZXhwIjoxNjUzMDE4ODQzfQ.Dega_zvBhNsRIEMDCTUWuq8qvrCe5gg1ZHzolScukls";
        //解析token获取负载中声明的对象
        Claims claims=Jwts.parser()
                .setSigningKey("xxxx")
                .parseClaimsJws(token)
                .getBody();
        System.out.println("id:"+claims.getId());
        System.out.println("subject:"+claims.getSubject());
        System.out.println("issuedAt:"+claims.getIssuedAt());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("签发时间:"+simpleDateFormat.format(claims.getIssuedAt()));
        System.out.println("过期时间:"+simpleDateFormat.format(claims.getExpiration()));
        System.out.println("当前时间:"+simpleDateFormat.format(new Date()));
    }
/**
     * 解析token(自定义申明)
     */
    @Test
    public void testParseTokenByClaims(){
        String token="eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI4ODg4Iiwic3ViIjoiUm9zZSIsImlhdCI6MTY1MzAyNzAyMSwicm9sZXMiOiJhZG1pbiIsImxvZ28iOiJ4eHguanBnIn0.XfV_XdI172FDwLfLs43kNUR74EJkYP0C7QLPk4_O3Lo";
        //解析token获取负载中声明的对象
        Claims claims=Jwts.parser()
                .setSigningKey("xxxx")
                .parseClaimsJws(token)
                .getBody();
        System.out.println("id:"+claims.getId());
        System.out.println("subject:"+claims.getSubject());
        System.out.println("issuedAt:"+claims.getIssuedAt());
        System.out.println("roles:"+claims.get("roles"));
        System.out.println("logo:"+claims.get("logo"));

    }

SpringSecurityOauth2整合JWT

JwtToken配置类

/**
 * JwtToken配置类
 * @auther lql
 * @create 2022-05-27 9:28
 **/
@Configuration
public class JwtTokenStoreConfig {
    @Bean
    public TokenStore jwtTokenStore(){
        return new JwtTokenStore(jwtAccessTokenConverter());
    }
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter(){
        JwtAccessTokenConverter accessTokenConverter=new JwtAccessTokenConverter();
        //配置Jwt使用的秘钥
        accessTokenConverter.setSigningKey("test_key");
        return accessTokenConverter;
    }
}

授权服务器配置类 

AuthorizationServerConfig 做如下修改

 扩展JWT中存储的内容

JWT内容增强器

/**
 * JWT内容增强器
 * @auther lql
 * @create 2022-05-28 16:04
 **/
public class JwtTokenEnhancer implements TokenEnhancer {

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
        Map<String,Object> info=new HashMap<>();
        info.put("enhance","enhance info");
        ((DefaultOAuth2AccessToken)oAuth2AccessToken).setAdditionalInformation(info);
        return oAuth2AccessToken;
    }
}
JwtToken配置类

授权服务器配置类修改如下

 解析JWT中内容

pom文件添加依赖


        <!--JWT依赖-->
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.0</version>
        </dependency>

修改UserController类,使用jjwt工具类来解析Authorization头中存储的JWT内容

package com.example.springsecurityoauth2demo.controller;

import io.jsonwebtoken.Jwts;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;

/**
 * @auther lql
 * @create 2022-05-20 16:17
 **/
@RestController
@RequestMapping("/user")
public class UserController {
    /**
     * 获取当前用户
     * @param authentication
     * @return
     */
    @RequestMapping("/getCurrentUser")
    public Object getCurrentUser(Authentication authentication, HttpServletRequest request){
        //解析JWT中的内容
        String head=request.getHeader("Authorization");
        String token=head.substring(head.indexOf("bearer")+7);
        return Jwts.parser()
                .setSigningKey("test_key".getBytes(StandardCharsets.UTF_8))
                .parseClaimsJws(token)
                .getBody();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值