springboot+jwt+redis验证登录状态

springboot+jwt放入redis中
redis的安装教程可以看历史
https://blog.csdn.net/qq_39990869/article/details/108000226
设置一个用于标示是否需要验证的注解类

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface AuthToken {

}

拦截器拦截所有的路径,再根据有上面注解的验证

@Configuration
public class WebAppConfiguration implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new AuthorizationInterceptor()).addPathPatterns("/**");
    }
}

controller类

@RestController
@Slf4j
@RequestMapping("/api/v1/")
public class UserController {
    @Autowired
    Md5TokenGenerator tokenGenerator;
    @Autowired
    TokenService tokenService;
    @Autowired
    UserMapper userMapper;
    @RequestMapping(value = "login", method = RequestMethod.POST)
    @ApiOperation("用户登录接口")
    public ResponseTemplate login( @RequestBody User user ) {
        String username = user.getUsername();
        String psd = user.getPassword();
        //判断是邮箱还是手机号的正则表达式
        String em = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
        String ph = "^[1][34578]\\d{9}$";
        JSONObject result = new JSONObject();
        //if(username.matches(ph)){//手机号登录
//            map.put("username", user);
//            map.put("password", psd);

//         User currentUser = users.get(0);
//             User user1=new User();


        if(user.getEmail()!=""&&user.getEmail()!=null){
            if(user.getEmail().matches(em)) {
                User users = userMapper.selectOne(user);
                if (users != null) {
                    Jedis jedis = new Jedis("172.16.238.157", 6379);
//jwt生成token存储到redis中
                    String token = tokenService.getToken(users);

                    jedis.set(users.getUsername(), token);
                    jedis.expire(users.getUsername(), ConstantKit.TOKEN_EXPIRE_TIME);
                    jedis.set(token, users.getUsername());
                    jedis.expire(token, ConstantKit.TOKEN_EXPIRE_TIME);
                    Long currentTime = System.currentTimeMillis();
                    jedis.set(token + users.getUsername(), currentTime.toString());
                    System.out.println(users.getUsername());
                    //用完关闭
                    jedis.close();
                    result.put("status", "登录成功");
                    result.put("token", token);
                } else {
                    result.put("status", "登录失败");
                }

            }
        }



        if(user.getPhone()!=""&&user.getPhone()!=null){
            if(user.getPhone().matches(ph)) {
                User users = userMapper.selectOne(user);
                if (users != null) {
                    Jedis jedis = new Jedis("172.16.238.157", 6379);
//jwt生成token存储到redis中
                    String token = tokenService.getToken(users);

                    jedis.set(users.getUsername(), token);
                    jedis.expire(users.getUsername(), ConstantKit.TOKEN_EXPIRE_TIME);
                    jedis.set(token, users.getUsername());
                    jedis.expire(token, ConstantKit.TOKEN_EXPIRE_TIME);
                    Long currentTime = System.currentTimeMillis();
                    jedis.set(token + users.getUsername(), currentTime.toString());
                    System.out.println(users.getUsername());
                    //用完关闭
                    jedis.close();
                    result.put("status", "登录成功");
                    result.put("token", token);
                } else {
                    result.put("status", "登录失败");
                }
            }

        }
        if(user.getUsername()!=""&&user.getUsername()!=null){
            User users = userMapper.selectOne(user);
        if (users != null) {
            Jedis jedis = new Jedis("172.16.238.157", 6379);
//jwt生成token存储到redis中
            String token = tokenService.getToken(user);

            jedis.set(username, token);
            jedis.expire(username, ConstantKit.TOKEN_EXPIRE_TIME);
            jedis.set(token, username);
            jedis.expire(token, ConstantKit.TOKEN_EXPIRE_TIME);
            Long currentTime = System.currentTimeMillis();
            jedis.set(token + username, currentTime.toString());
            System.out.println(users.getUsername());
            //用完关闭
            jedis.close();
            result.put("status", "登录成功");
            result.put("token", token);
        } else {
            result.put("status", "登录失败");
        }

        }
        //}
        return ResponseTemplate.builder()
                .data(result)
                .build();
    }

       @ApiOperation("测试token接口")
    @RequestMapping(value = "test", method = RequestMethod.GET)
    @AuthToken
    public ResponseTemplate test() {
        List<User> user = new User().selectAll();
        return ResponseTemplate.builder()
                .code(200)
                .message("Success")
                .data(user)
                .build();
    }
}

拦截后进行判断是否存在token

@Slf4j
public class AuthorizationInterceptor implements HandlerInterceptor {

@Autowired
    UserMapper userMapper;
    //存放鉴权信息的Header名称,默认是Authorization
    private String httpHeaderName = "Authorization";

    //鉴权失败后返回的错误信息,默认为401 unauthorized
    private String unauthorizedErrorMessage = "401 unauthorized";

    //鉴权失败后返回的HTTP错误码,默认为401
    private int unauthorizedErrorCode = HttpServletResponse.SC_UNAUTHORIZED;

    /**
     * 存放登录用户模型Key的Request Key
     */
    public static final String REQUEST_CURRENT_KEY = "REQUEST_CURRENT_KEY";


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

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method        method        = handlerMethod.getMethod();
        // 如果打上了AuthToken注解则需要验证token
        if (method.getAnnotation(AuthToken.class) != null || handlerMethod.getBeanType().getAnnotation(AuthToken.class) != null) {


            String token = request.getHeader(httpHeaderName);
            log.info("token is {}", token);
            String username = "";
            Jedis  jedis    = new Jedis("172.16.238.157", 6379);
            if (token != null && token.length() != 0) {

                username = jedis.get(token);
              
                log.info("username is {}", username);

            }

            if (username != null && !username.trim().equals("")) {

                    //log.info("token birth time is: {}",jedis.get(username+token));
                    Long tokeBirthTime = Long.valueOf(jedis.get(token + username));
                    log.info("token Birth time is: {}", tokeBirthTime);
                    Long diff = System.currentTimeMillis() - tokeBirthTime;
                    log.info("token is exist : {} ms", diff);
                    if (diff > ConstantKit.TOKEN_RESET_TIME) {
                        jedis.expire(username, ConstantKit.TOKEN_EXPIRE_TIME);
                        jedis.expire(token, ConstantKit.TOKEN_EXPIRE_TIME);
                        log.info("Reset expire time success!");
                        Long newBirthTime = System.currentTimeMillis();
                        jedis.set(token + username, newBirthTime.toString());
                    }

                    //用完关闭
                    jedis.close();
                    request.setAttribute(REQUEST_CURRENT_KEY, username);
                    return true;


            } else {
                JSONObject jsonObject = new JSONObject();

                PrintWriter out = null;
                try {
                    response.setStatus(unauthorizedErrorCode);
                    response.setContentType(MediaType.APPLICATION_JSON_VALUE);

                    jsonObject.put("code", ((HttpServletResponse) response).getStatus());
                    jsonObject.put("message", HttpStatus.UNAUTHORIZED);
                    out = response.getWriter();
                    out.println(jsonObject);

                    return false;
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (null != out) {
                        out.flush();
                        out.close();
                    }
                }

            }

        }

        request.setAttribute(REQUEST_CURRENT_KEY, null);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

jwt生成

@Service
public class TokenServiceImpl implements  TokenService{
    @Autowired
    UserMapper userMapper;
    @Override
    public String getToken(User user) {
        Date start = new Date();
        long currentTime = System.currentTimeMillis() + 60* 60 * 1000;//一小时有效时间
        Date end = new Date(currentTime);

        String token = "";
//将username或者其他的表示放入token中这样就能够进行判断,放username或者id都行,只要是唯一标示
        token = JWT.create().withAudience(user.getUsername()).withIssuedAt(start).withExpiresAt(end)
                .sign(Algorithm.HMAC256(user.getPassword()));
        return token;
    }
}

你可能感兴趣的:(redis,jedis,jwt,java)