从过滤器迁移到拦截器会导致403错误

时间:2019-03-14 20:18:27

标签: java spring spring-security

在我的Spring Boot应用程序中,我正在使用以下Filter处理JWT:

(为简便起见,省略了不相关的代码)

@Component
public class JwtFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(
            HttpServletRequest request, HttpServletResponse response,
            FilterChain filterChain) throws ServletException, IOException {

        // processing the JWT from the request

        Authentication auth =
            new UsernamePasswordAuthenticationToken(username, password, roles);
        SecurityContextHolder.getContext().setAuthentication(auth);

        filterChain.doFilter(request, response);
    }
}

这很完美,但是我想将此功能迁移到拦截器,所以我只是将相同的逻辑添加到HandlerInterceptor

@Component
public class JwtInterceptor implements HandlerInterceptor {

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

        // processing the JWT from the request

        Authentication auth =
            new UsernamePasswordAuthenticationToken(username, password, roles);
        SecurityContextHolder.getContext().setAuthentication(auth);

        return true;
    }
}

但是在这种情况下,我总是收到403禁止响应我的请求。

我已经调试了JwtInterceptor,它似乎工作正常。

preHandle()已完全执行,使用正确的setAuthentication()参数调用了auth,该函数返回了true

因此,我猜想Authentication在执行此拦截器后会“丢失”,但是我无法弄清楚原因,在这一点上,我真的不知道如何进一步调试。

我非常感谢您提供有关如何解决此问题的建议(甚至只是如何弄清楚问题出在哪里)。

0 个答案:

没有答案
相关问题