Spring security 如果尝试身份验证未成功,如何在筛选器中返回401状态

Spring security 如果尝试身份验证未成功,如何在筛选器中返回401状态,spring-security,exception-handling,jwt,Spring Security,Exception Handling,Jwt,我正在尝试覆盖类JWTAuthenticationFilter扩展的UsernamePasswordAuthenticationFilter中的尝试验证方法 但如果登录名和密码不正确,它将返回500状态。如何退还401 @Override public Authentication attemptAuthentication(HttpServletRequest req, HttpServl

我正在尝试覆盖
类JWTAuthenticationFilter扩展的UsernamePasswordAuthenticationFilter中的
尝试验证
方法 但如果登录名和密码不正确,它将返回500状态。如何退还401

 @Override
    public Authentication attemptAuthentication(HttpServletRequest req,
                                                HttpServletResponse res) throws AuthenticationException {
        try {
            ApplicationUser creds = new ObjectMapper()
                    .readValue(req.getInputStream(), ApplicationUser.class);

            return authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            creds.getUsername(),
                            creds.getPassword(),
                            new ArrayList<>())
            );
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
@覆盖
公共身份验证尝试身份验证(HttpServletRequest-req,
HttpServletResponse(res)引发AuthenticationException{
试一试{
ApplicationUser creds=new ObjectMapper()
.readValue(req.getInputStream(),ApplicationUser.class);
返回authenticationManager.authenticate(
新用户名PasswordAuthenticationToken(
creds.getUsername(),
creds.getPassword(),
新建ArrayList())
);
}捕获(例外e){
抛出新的运行时异常(e);
}
}

更改异常类

}catch (IOException e){ 

使其返回401。但是为什么呢?

是AuthenticationException让它返回401。若捕获异常,它也将捕获AuthenticationException。

删除是不可能的,因为超类不支持我的特定IOException。我自己的AuthenticationException catch子句可以工作,但是如果我可以在
IOException
上更改
Exception
,为什么要这样做呢。因此,当AuthenticationException发生时,它会进一步上升。现在我不明白为什么了。啊,我不知道你需要抓住我。是的,那就是正确的方法。我将从我的答案中删除这一部分。