JWT+Redis验证实现(Springboot)

思路

        JWT生成token,token存redis中,验证时从token取出比对,相同延长过期时间,不同则返回错误信息,删除redis中的该数据。reids比对这一步在我的想法里,是防止同一用户在不同设备同时登录,我认为这是不合理的,在同一时间,同一用户只有一个token是有效的,而不是token信息正确就可以通过验证。

JWTUtil
package cn.practical.practicalbackend.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Map;

@Component
public class JWTUtil {

    private static final String SECRET_KEY = "PracticalBackendSecretKey";

    public static String generateToken(Map<String, String> map) {


        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.HOUR, 1);

        JWTCreator.Builder builder = JWT.create();

        map.forEach(builder::withClaim);
        return builder.withIssuer("WhiVanilla")
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SECRET_KEY));
    }

    public static DecodedJWT verifyToken(String token) {


        if (token != null && !token.isEmpty()) {

            try {
                return JWT.require(Algorithm.HMAC256(SECRET_KEY))
                        .withIssuer("WhiVanilla")
                        .build()
                        .verify(token);
            } catch (TokenExpiredException e) {
                throw new TokenExpiredException("token 过期!");
            } catch (JWTVerificationException e) {
                throw new JWTVerificationException("token 无效!", e);
            }
        } else {
            throw new TokenExpiredException("token 为空!");
        }
    }

}
JWTInterceptor
package cn.practical.practicalbackend.interceptor;

import cn.practical.practicalbackend.common.utils.JWTUtil;
import cn.practical.practicalbackend.common.utils.RequestHolder;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class JWTInterceptor implements HandlerInterceptor {

    @Resource
    RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        RequestHolder.saveRequest(request);

        Map<String, Object> map = new HashMap<>();
        String token = request.getHeader("token");

        // 检查token是否为空
        if (token == null || token.isEmpty()) {
            map.put("msg", "miss token!");
            map.put("status", false);
            String json = new ObjectMapper().writeValueAsString(map);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().println(json);
            return false;
        }

        try {
            DecodedJWT jwt = JWTUtil.verifyToken(token);

            String account = jwt.getClaim("account").asString();
            String s = (String) redisTemplate.opsForValue().get(account);
            if (s != null) {
                if (s.equals(token)) {
                    redisTemplate.expire(account, 1, TimeUnit.HOURS);
                } else {
                    redisTemplate.delete(account);
                    throw new Exception("已在其他设备登录!");
                }
                return true;
            } else {
                throw new TokenExpiredException("token无效!");
            }
        } catch (SignatureVerificationException e) {
            log.error(e.getMessage());
            map.put("msg", "无效签名!");
        } catch (TokenExpiredException e) {
            log.error(e.getMessage());
            map.put("msg", "token过期!");
        } catch (AlgorithmMismatchException e) {
            log.error(e.getMessage());
            map.put("msg", "算法不一致!");
        } catch (Exception e) {
            log.error(e.getMessage());
            map.put("msg", "token无效!");
        }

        map.put("status", false);
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().println(json);
        return false;
    }
}
登录逻辑实现
 @Override
    public ApiResult login(String account, String password) {
        // 对密码进行MD5加密
        password = MD5Util.md5(password);

        // 根据加密后的密码和账户在数据库中查找用户
        User userDB = userMapper.login(account, password);

        // 如果用户存在
        if (userDB != null) {
            // 创建返回结果的map
            Map<String, Object> map = new HashMap<>();

            try {
                // 创建JWT的负载信息
                Map<String, String> payload = new HashMap<>();
                payload.put("account", userDB.getAccount());

                // 生成JWT令牌
                String token = JWTUtil.generateToken(payload);

                // 从Redis中获取存储的令牌
                String s = (String) redisTemplate.opsForValue().get(account);

                if (s != null) { // 如果Redis中已经存在令牌
                    if (s.equals(token)) { // 令牌匹配,更新过期时间
                        redisTemplate.expire(account, 1, TimeUnit.HOURS);
                    } else { // 令牌不匹配,说明在其他设备上已经登录
                        redisTemplate.delete(account); // 删除现有的令牌
                        throw new Exception("已在其他设备登录!"); // 抛出异常
                    }
                } else { // 如果Redis中不存在令牌
                    // 在Redis中存储新的令牌,并设置过期时间为1天
                    redisTemplate.opsForValue().set(account, token, 1, TimeUnit.HOURS);

                    CompletableFuture.runAsync(() -> {
                        boolean msg = userMapper.LoginTimeSet(userDB.getAccount(), new Date());
                    }, executor);

                }

                // 将状态、令牌和用户信息存入map
                map.put("status", true);
                map.put("token", token);
                map.put("user", userDB.toUserVO());

            } catch (Exception e) { // 捕获异常
                // 如果有异常发生,返回状态为false,并存储异常信息
                map.put("status", false);
                map.put("msg", e.getMessage());
            }

            // 返回成功的ApiResult,并包含map中的数据
            return ApiResult.success(map);
        }

        // 如果用户不存在,抛出登录失败的异常
        return ApiResult.failed("login fail!");
    }
 配置拦截器
package cn.practical.practicalbackend.config;

import cn.practical.practicalbackend.interceptor.JWTInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Resource
    JWTInterceptor jwtInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/user/register", "/user/login", "/user/logout");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值