一、使用场景

当用户登录成功后,如果一段时间不去调用其他接口,就会返回token过期,请重新登录!!

二、代码实现

首先:通过用户名和密码判断用户是否登录成功,如果登录成功,就设置一个token和token过期时间放到缓存当中,这里设定的token过期时间为两分钟

public JSONObject getLogin(String userName,String password) {
        JSONObject result = new JSONObject();
        ValueOperations<String,Object> vo = redisTemplate.opsForValue();
        String token = String.valueOf(UUID.randomUUID());
        if(userName.equals("用户名") && password.equals("密码")){
            vo.set(token,userName,2, TimeUnit.MINUTES);
            result.put("userName",userName);
            result.put("token",token);
            result.put("resultCode", 200);
            result.put("resultMsg", "登录成功!");
        }else {
            result.put("resultCode", 500);
            result.put("resultMsg", "登录失败!");
        }
        return result;
    }

然后:给其他接口设置拦截器,告诉前端调用其他接口的时候需要带上登录接口返回的token在Header当中,如果缓存当中的值和前端所传的值是一样的,那么更新缓存当中的token,防止过期

package com.hhubrain.Interceptor;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.concurrent.TimeUnit;


public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            JSONObject result  = new JSONObject();
            result.put("returnCode",404);
            result.put("returnMsg","用户未登录,请登录后操作!");
            return false;
        }
        ValueOperations<String,Object> vo = redisTemplate.opsForValue();
        Object loginStatus = vo.get(token);
        if( Objects.isNull(loginStatus)){
            JSONObject result  = new JSONObject();
            result.put("returnCode",500);
            result.put("returnMsg","token已经过期,请重新登录");
            response.getWriter().print(result);
            return false;
        }
        redisTemplate.expire(token,2, TimeUnit.MINUTES);
        return true;
    }

}
package com.hhubrain.config;

import com.hhubrain.Interceptor.AuthInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


@Configuration
public class AuthConfig implements WebMvcConfigurer {
    @Bean
    public AuthInterceptor initAuthInterceptor(){
        return new AuthInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //addPathPatterns:哪些路径下的会被拦截 /api/getTest
        //excludePathPatterns:哪些路径下不会被拦截 /api/insertRedisTest
        registry.addInterceptor(initAuthInterceptor()).addPathPatterns("接口路径").excludePathPatterns("接口路径");
    }
}

最后:调用测试接口,Header当中带上token值

@GetMapping("/getTest")
    public String getTest() {
        return "通过token登录成功";
    }
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐