Spring Security采用JWT验证时filter异常处理和JWT续期问题

问题描述

security+jwt进行身份认证授权时,在登录前通常增加一个jwtfilter进行jwt验证,filter中的异常并不会被全局异常捕获,导致返回数据格式与统一格式不对

具体描述为: jwtfilter中对分发的token进行验证时抛出的异常捕获统一返回

问题出现原因

通常的filter时java web提供,并不被spring接管

解决方案 将异常抛给controller

JWTFilter中处理异常并跳转到异常处理控制器,再由控制器抛出异常,最终被全局异常捕获,统一返回格式

jwt验证时通常会抛出4中异常

  • ExpiredJwtException token过期时抛出
  • MalformedJwtException token的格式错误,即token被篡改
  • SignatureException token签名错误,生成 token 和解析 token 使用的 SECRET 签名不一致就会报这个错误
  • UnsupportedJwtException jwt不支持

在进行jwt验证时捕获这4种异常,再处理异常信息抛给controller处理

具体步骤

1 在JwtAuthenticationTokenFilter extends OncePerRequestFilter 中
try {
                Claims claims = JwtUtil.parseJWT(token);
}catch (ExpiredJwtException exception){
                log.error("身份验证过期"+exception);
                request.setAttribute("jwtFilter.error",new BaseException("身份验证过期"));
                request.getRequestDispatcher("/error/jwtFilter").forward(request,response);
}catch (MalformedJwtException exception){
                log.error("JWT Token格式不对"+exception);
                request.setAttribute("jwtFilter.error",new BaseException("JWT Token格式不对"));
                request.getRequestDispatcher("/error/jwtFilter").forward(request,response);
}catch (SignatureException exception){
                //生成 token 和解析 token 使用的 SECRET 签名不一致就会报这个错误
                log.error("JWT 签名错误"+exception);
                request.setAttribute("jwtFilter.error",new BaseException("JWT 签名错误"));
                request.getRequestDispatcher("/error/jwtFilter").forward(request,response);
}catch (UnsupportedJwtException exception){
                log.error("不支持的 Jwt "+exception);
                request.setAttribute("jwtFilter.error",new BaseException("不支持的 Jwt"));
                request.getRequestDispatcher("/error/jwtFilter").forward(request,response);
}catch (Exception e) {
                log.error("jwt验证:"+e);
                request.setAttribute("jwtFilter.error",new BaseException("JWT 验证失败"));
                request.getRequestDispatcher("/error/jwtFilter").forward(request,response);
          
}
2 FilterExceptionController 中 最终被抛出,会被全局异常处理器处理返回统一的数据格式
    @RequestMapping("/error/jwtFilter")
    public void jwtFilterException(HttpServletRequest reques){
        log.warn("jwt controller ");
        Exception e = (Exception) reques.getAttribute("jwtFilter.error");
        log.warn(e.getMessage());
        throw e;
    }

其他相关

security在认证授权时抛出的异常

认证时 重写 AuthenticationEntryPoint

授权时 重写 AccessDeniedHandler

@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json");
        httpServletResponse.getWriter().println(JSON.toJSON(BaseResponse.fail("1005",e.getMessage())));
        httpServletResponse.getWriter().flush();
    }
}



@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json");
        httpServletResponse.getWriter().println(JSON.toJSON(BaseResponse.fail("1004",e.getMessage())));
        httpServletResponse.getWriter().flush();
    }
}

在security配置中加入

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)//EnableGlobalMethodSecurity开启全局方法级别授权控制,prePostEnabled在执行方法前进行授权
public class SecurityConfig  extends WebSecurityConfigurerAdapter {
     @Override
    protected void configure(HttpSecurity http) throws Exception {
      //认证失败时的提示返回自定义信息
        http.exceptionHandling()
                .accessDeniedHandler(customAccessDeniedHandler)
                .authenticationEntryPoint(customAuthenticationEntryPoint);


    }
}

JWT续期问题

当jwt token快过期时,可以选择不续期,那么过期后需要用户重新登录再次下发token

续期方案

1 每次请求时续期 【完全不考虑】

即每次请求都重新下发新的token

缺点:下发频率太高,影响性能

2 快过期时续期【可以考虑】

比如30分钟过期时间,当还剩10分钟以内时请求过来进行续期

缺点:

        a. 泄露后容易导致token一直活跃

        b. 且如果是并发请求,容易导致下发多个token        

关于该方案泄露的补丁

可以在token中添加ip或者地域等信息【这些信息应该被加密】,一旦改变ip或者地域就需要重新登录

但是这样如果客户经常更换ip,就需要频繁登录,体验感会不好;可以让用户选择安全模式,如果选择安全模式就需要这样

3 双token【可以考虑】

登录时一次下发两个token

token1用于用户认证,过期时间设置短些,比如1个小时

token2用于续期,过期时间可以设置长些,比如1天

token2的key可以根据自己的习惯设置,可以设置一为无相关性的key,这样能在一定程度上混淆

过程:

登录请求返回 token1、token2和token1的过期时间

前端判断,当token1快过期了,携带token2请求

后端根据token2重新续期token1

缺点:

        前端每次请求都需要先判断token1是否快过期

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值