当前位置 : 主页 > 编程语言 > java >

权限校验

来源:互联网 收集:自由互联 发布时间:2023-12-16
(权限校验) 1. 拦截器开发 @Componentpublic class LoginAuthInterceptor implements HandlerInterceptor { @Resource private RedisTemplateString, String redisTemplate; @Override public boolean preHandle(HttpServletRequest request, HttpSe

(权限校验)

1. 拦截器开发

@Component
public class LoginAuthInterceptor implements HandlerInterceptor {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求方式
        //如果请求方式是options 预检请求,直接放行
        String method = request.getMethod();
        if ("OPTIONS".equals(method)) {
            return true;
        }
        //从请求头获取token
        String token = request.getHeader("token");
        //如果token为空,返回错误信息
        if (StrUtil.isEmpty(token)) {
            responseNoLoginInfo(response);
            return false;
        }
        //如果token不为空,拿到token查询redis
        String userInfoString = redisTemplate.opsForValue().get(RedisEnum.USER_LOGIN.getValue() + token);
        //如果redis查询不到数据,返回错误信息
        if (StrUtil.isEmpty(userInfoString)) {
            responseNoLoginInfo(response);
            return false;
        }
        //如果redis查询到用户信息,把用户信息放到ThreadLocal里面
        SysUser sysUser = JSON.parseObject(userInfoString, SysUser.class);
        AuthContextUtil.set(sysUser);
        //把redis用户信息数据更新过期时间
        redisTemplate.expire(RedisEnum.USER_LOGIN.getValue() + token, 30, TimeUnit.MINUTES);
        //放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        //ThreadLocal数据删除
        AuthContextUtil.remove();
    }

    //响应208状态码给前端
    private void responseNoLoginInfo(HttpServletResponse response) {
        Result<Object> result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}

2. 拦截器注册

@Component
public class WebMvcConfiguration implements WebMvcConfigurer {

    @Resource
    private LoginAuthInterceptor loginAuthInterceptor;
    @Resource
    private UserProperties userProperties;

    /**
     * 拦截器注册
     * @param registry
     * @time: 2023/12/4 11:33
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginAuthInterceptor)
                .excludePathPatterns(userProperties.getNoAuthUrls())
                .addPathPatterns("/**");
    }

    /**
     * 跨域
     * @param registry
     * @time: 2023/12/4 11:31
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")      // 添加路径规则
                .allowCredentials(true)           // 是否允许在跨域的情况下传递Cookie
                .allowedOriginPatterns("*")       // 允许请求来源的域规则
                .allowedMethods("*")
                .allowedHeaders("*") ;            // 允许所有的请求头
    }
}

3. 配置noAuthUrls

我们接入了swagger,需要根据swagger版本配置相应的路径

auth:
    noAuthUrls:
      - /admin/system/index/login
      - /admin/system/index/generateValidateCode
      - /swagger-resources/**
      - /doc.html/**
      - /v3/**
【文章原创作者盐城网站设计 http://www.1234xp.com/yancheng.html 提供,感恩】
上一篇:Java并发编程的进阶之旅
下一篇:没有了
网友评论