如果attemptAuthentication不成功,如何在Filter中返回401状态

时间:2018-01-03 16:41:32

标签: spring-security exception-handling jwt

我试图覆盖attemptAuthentication中的class JWTAuthenticationFilter extends 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);
        }
    }

2 个答案:

答案 0 :(得分:0)

更改例外类

}catch (IOException e){ 

让它返回401.但为什么??

答案 1 :(得分:0)

使用AuthenticationException使其返回401.如果捕获Exception,它也将捕获AuthenticationException。