springboot拦截器验证token实现登陆

最近在做一个官网登陆认证项目,因为登陆以后无需太多的角色校验,所以改成角色简单实现就好,没有用太多框架组件,只用原声写。
springboot拦截器验证token实现登陆_第1张图片
直接上代码:
首先我用的是前后端分离的,所以要解决跨域问题

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "DELETE", "PUT","PATCH")
                .allowedHeaders("*")
                //cookie设置
                .allowCredentials(true).maxAge(3600);
    }

其次是使用springmvc的拦截器拦截登陆,所以要配置拦截器

@Configuration
public class WebAppConfig extends WebMvcConfigurerAdapter {
    // 多个拦截器组成一个拦截器链
    // addPathPatterns 用于添加拦截规则
    // excludePathPatterns 用户排除拦截

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())//添加拦截器
                .excludePathPatterns("/loginOK")//对应的不拦截的请求

                .addPathPatterns("/**"); //拦截所有请求
    }
}

要对用户登陆放行,拿到token直接可以登录,否则拦截,跳转登陆

@GetMapping("/loginOK")
    @ResponseBody
    public String loginOK(HttpServletRequest httpServletRequest){
        HttpSession session = httpServletRequest.getSession();
        session.setAttribute("sessions","mytoken");
        System.out.println(session.getId());
        return "mytoken";
    }

接下来就是重点拦截器的写法

/**
 * @Auther: sgy
 * @Date: 2019/12/9 22:08
 * @Description: TODO  模拟官网简单登陆,拦截器session效验token
 * @version: V1.0
 */
public class LoginInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(LoginInterceptor.class);
    /**
     * 进入controller层之前拦截请求
     *
     * @param httpServletRequest
     * @param
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse response, Object o) throws Exception {
        String header = httpServletRequest.getHeader("Authorization");
        String method = httpServletRequest.getMethod();
        //处理预请求
        if (HttpMethod.OPTIONS.toString().equals(method)) {
            return true;
        }
        else {
            HttpSession session = httpServletRequest.getSession();
            String id = session.getId();
            System.out.println(id);
            String sessions = (String) session.getAttribute("sessions");
            if (sessions.equals(header)) {
                return true;
            }
        }
        log.info("---------------开始进入地址拦截器-------------------"+header);
        return false;
    }
    //访问controller之后 访问视图之前被调用
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        log.info("--------------处理请求完成后视图渲染之前的处理操作---------------");
    }
    //访问视图之后被调用
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        log.info("---------------视图渲染之后的操作-------------------------0");
    }
}

不知道预请求是啥的请看这篇文章
https://www.cnblogs.com/ermaoblog/p/8855915.html

亲测有效,前段代码就不展示了,自己用postman测试就可以
如果能帮到你,请点个赞吧

你可能感兴趣的:(java)