工具类:JWT(0.12.3)

发布于:2024-10-11 ⋅ 阅读:(120) ⋅ 点赞:(0)

依赖

    <!--     创建、解析 和 验证JSON Web Tokens (JWT)-->
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.12.3</version>
        </dependency>

application.yml文件配置

jwt:
    # 设置jwt签名加密时使用的秘钥   HMAC-SHA算法32字节
    admin-secret-key: 1ost-very-long-and-secure-secret-key-32-bytes
    # 设置jwt过期时间
    admin-ttl: 7200000
    # 设置前端传递过来的令牌名称
    admin-token-name: token

JwtProperties.java

package com.nnutc.system.config;

@Configuration
@ConfigurationProperties(prefix = "jwt")
@Component // 或者使用 @Configuration(proxyBeanMethods = false) 并依赖注入到需要的地方
public class JwtProperties {

    private String adminSecretKey;
    private long adminTtl;
    private String adminTokenName;

    // Getters and Setters
    public String getAdminSecretKey() {
        return adminSecretKey;
    }

    public void setAdminSecretKey(String adminSecretKey) {
        this.adminSecretKey = adminSecretKey;
    }

    public long getAdminTtl() {
        return adminTtl;
    }

    public void setAdminTtl(long adminTtl) {
        this.adminTtl = adminTtl;
    }

    public String getAdminTokenName() {
        return adminTokenName;
    }

    public void setAdminTokenName(String adminTokenName) {
        this.adminTokenName = adminTokenName;
    }
}

JwtUtil.java

package com.nnutc.common.utils;

public class JwtUtil {
    /**
     * 生成jwt
     * 使用Hs256算法,私钥使用固定密钥
     * @param secretKey  jwt密钥
     * @param ttlMillis  jwt过期时间,单位毫秒
     * @param claims     设置的信息
     * @return
     */
    public static String createJWT(String secretKey, long ttlMillis, Map<String, Object> claims){
        //指定加密算法
        SecureDigestAlgorithm<SecretKey, SecretKey> algorithm = Jwts.SIG.HS256;
        //生成JWT的时间
        long expMillis = System.currentTimeMillis()+ttlMillis;
        Date exp = new Date(expMillis);
        //密钥实例
        SecretKey key = Keys.hmacShaKeyFor(secretKey.getBytes());

        String compact = Jwts.builder()
                .signWith(key, algorithm) //设置签名使用的签名算法和签名使用的秘钥
                //如果有私有声明,一点要先设置这个自己创建的私有的声明,这个是给builder的claims赋值,一旦卸载标准的声明赋值之后,就是覆盖了那些标准的声明的
                .expiration(exp)
                .claims(claims) //设置自定义负载信息
                .compact();//设置过期时间
        return compact;
    }


    /**
     * 解析jwt
     * @param token
     * @param secretKey
     * @return
     */
    public static Jws<Claims> parseJWT(String token, String secretKey){
        //密钥实例
        SecretKey key = Keys.hmacShaKeyFor(secretKey.getBytes());

        Jws<Claims> claimsJws = Jwts.parser()
                .verifyWith(key)  //设置签名的密钥
                .build()
                .parseSignedClaims(token); //设置要解析的jwt

        return claimsJws;
    }
}

controller类

String jsonString = JSON.toJSONString(customUserDetails);
        Map<String, Object> claims = new HashMap<>();
        claims.put("customUserDetails", jsonString); // 你可以添加其他信息

String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

过滤器

package com.nnutc.system.filter;


@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String uri = request.getRequestURI();
        if (uri.equals("/admin/system/index/login")) {//直接放行
            filterChain.doFilter(request, response);
            return;
        }
        String token = request.getHeader("Authorization");

        if (!StringUtils.hasText(token)) {//header中没有token
            throw new RuntimeException("Token为空");
        }
        try{
            Jws<Claims> claims = JwtUtil.parseJWT(token, jwtProperties.getAdminSecretKey());

            filterChain.doFilter(request, response);//放行
        }catch (Exception e){
            throw new RuntimeException(e);

        }
    }
}

网站公告

今日签到

点亮在社区的每一天
去签到