SpringBoot集成token验证

下面我们说一下SpringBoot如何集成token验证

1、向pom文件引入依赖

 		<dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.0</version>
        </dependency>

2、工具类编写

package com.pro.work.sweet.utils;


import com.alibaba.fastjson.JSON;
import com.pro.work.sweet.entity.TokenInfo;
import com.pro.work.sweet.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

public class TokenUtil {
    @Autowired
    private RedisUtil redisUtil ;
    /**
     * 签名秘钥,可以换成 秘钥 注入
     */
    public static final String SECRET = "test";//注意:本参数需要长一点,不然后面剪切的时候很可能长度为0,就会报错
    /**
     * 签发地
     */
    public static final String issuer = "com.pro.work.sweet";
    /**
     * 过期时间
     */
    public static final long ttlMillis = 3600*1000*60;

    /**
     * 生成token
     *
     * @return
     */
    public static String createJwtToken(String subject,User user) {
        return createJwtToken( issuer, subject, ttlMillis,user);
    }
    public static String createJwtToken(User user) {
        return createJwtToken( issuer, "", ttlMillis,user);
    }

    /**
     * 生成Token
     * @param issuer  该JWT的签发者,是否使用是可选的
     * @param subject  该JWT所面向的用户,是否使用是可选的;
     * @param ttlMillis 签发时间 (有效时间,过期会报错)
     * @return token String
     */
    public static String createJwtToken(String issuer, String subject, long ttlMillis,User user) {

        // 签名算法 ,将对token进行签名
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        // 生成签发时间
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        // 通过秘钥签名JWT
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SECRET);
        String str=signatureAlgorithm.getJcaName();
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, str);

        // 让我们设置JWT声明
        if(null != user){
            JwtBuilder builder = Jwts.builder().setId(user.getIntId())
                    .setIssuedAt(now)
                    .setSubject(subject)
                    .setIssuer(issuer)
                    .signWith(signatureAlgorithm, signingKey);
            // if it has been specified, let's add the expiration
            if (ttlMillis >= 0) {
                //过期时间
                long expMillis = nowMillis + ttlMillis;
                Date exp = new Date(expMillis);
                builder.setExpiration(exp);
            }

            // 构建JWT并将其序列化为一个紧凑的url安全字符串
            return builder.compact();
        }else{
            return null ;
        }
    }

    /**
     * Token解析方法
     * @param jwt Token
     * @return
     */
    public static Claims parseJWT(String jwt) {
        // 如果这行代码不是签名的JWS(如预期),那么它将抛出异常
        Claims claims  = Jwts.parser()
                    .setSigningKey(DatatypeConverter.parseBase64Binary(SECRET))
                    .parseClaimsJws(jwt).getBody();
        return claims;
    }

    @SneakyThrows
    public void checkTokenIsLev(String token){
        Claims claims = parseJWT(token) ;
        if(!token.equals(JSON.parseObject(String.valueOf(redisUtil.get(claims.getId())), TokenInfo.class).getToken())){
            throw new Exception("您已离线,请重新登录") ;
        }
    }

}

我的 token工具类主要是契合redis进行登录验证,所以契合了user这个对象进来,大家使用的时候如果不必要的话可以去掉,并不难

下面是我写的controller验证类,需要的可以看一下,不过我建议还是按自己的逻辑写好一些

package com.pro.work.sweet.controller;

import com.alibaba.fastjson.JSON;
import com.pro.work.sweet.entity.TokenInfo;
import com.pro.work.sweet.entity.User;
import com.pro.work.sweet.service.UserService;
import com.pro.work.sweet.utils.RedisUtil;
import com.pro.work.sweet.utils.ResponseMessage;
import com.pro.work.sweet.utils.TokenUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/token")
public class TokenController {
    @Autowired
    private UserService userService ;
    @Autowired
    private RedisUtil redisUtil ;
    @SneakyThrows
    @PostMapping("/login")
    public ResponseMessage loginAndSetToken(@RequestBody User user){
        User loginUser = userService.login(user) ;
        TokenInfo tokenInfo = new TokenInfo() ;
        try {
            tokenInfo.setToken(TokenUtil.createJwtToken(loginUser));
        }catch (Exception e){
            throw new Exception("生成token失败,请重新登录") ;
        }
        tokenInfo.setUser(loginUser);
        // 向redis中存储用户信息和对应的Token
        redisUtil.set(loginUser.getIntId(),JSON.toJSONString(tokenInfo),3600*1000*60) ;
        return ResponseMessage.success(tokenInfo) ;
    }

    @SneakyThrows
    @PostMapping("/checkToken")
    public ResponseMessage checkToken(@RequestBody TokenInfo tokenInfo){
        TokenInfo tokenInfoForRedis = JSON.parseObject(String.valueOf(redisUtil.get(TokenUtil.parseJWT(tokenInfo.getToken()).getId())),TokenInfo.class) ;
        TokenInfo tokens = new TokenInfo() ;
        if(tokenInfoForRedis != null){
            tokens.setUser(tokenInfoForRedis.getUser());
            tokens.setToken(tokenInfo.getToken());
            return ResponseMessage.success(tokens) ;
        }else{
            throw new Exception("您已离线,请重新登录") ;
        }
    }
}

至此,后台的token集成完毕


版权声明:本文为dxy3166216191原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。