Spring Security UsernamePasswordAuthenticationFilter:登录失败后如何访问Request

mps*_*tos 3 spring spring-security

我正在使用 Angular 7 和 Spring Boot 实现一个登录页面,并且正在处理登录失败。基本上我想在 X 次登录尝试失败后锁定登录一段特定的时间。

Http安全配置

@Override
    protected void configure(HttpSecurity http) throws Exception {
        logger.info("#### Configuring Security ###");
        JWTAuthenticationFilter jwtAuthenticationFilter = new JWTAuthenticationFilter(authenticationManager());
        jwtAuthenticationFilter.setFilterProcessesUrl("/rest/users/authenticate");//this override the default relative url for login: /login

        http
            .httpBasic().disable()
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/rest/", "/rest/helloworld/**").permitAll()
            .anyRequest().authenticated()
            .and().exceptionHandling().authenticationEntryPoint(new JwtAuthenticationEntryPoint()).and()
            .addFilter(jwtAuthenticationFilter);
Run Code Online (Sandbox Code Playgroud)

为了处理登录,我创建了一个过滤器

public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    private static Logger logger = Logger.getLogger(JWTAuthenticationFilter.class);

    private AuthenticationManager authenticationManager;

    public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;

    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        try {
            UserDto credentials = new ObjectMapper().readValue((request.getInputStream()), UserDto.class);            
            return authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                    credentials.getUserName(),
                    credentials.getPassword(),
                    new ArrayList<>())
            );
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        //sucessfull authentication stuff
    }


    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        logger.info("Authentication failed");

        ErrorMessage errorMessage = new ErrorMessage("access_denied", "Wrong email or password.");
        String jsonObject = JSONUtil.toJson(errorMessage);

        //processing authentication failed attempt
        UserDto credentials = new ObjectMapper().readValue((request.getInputStream()), UserDto.class);
        AuthenticationService authenticationService = Application.getApplicationContext().getBean(AuthenticationService.class);
        int numFailedAttemptLogin = authenticationService.authenticationFailedAttempt(credentials.getUserName());

        response.setStatus(403);
        PrintWriter out = response.getWriter();
        out.print(jsonObject);
        out.flush();
        out.close();

        //super.unsuccessfulAuthentication(request, response, failed);
    }
}
Run Code Online (Sandbox Code Playgroud)

登录工作正常,没有任何问题。我的问题是不成功的身份验证方法。当用户输入错误的凭据时,将引发 BadCredentials 异常并调用unsuccessfulAuthentication方法。在这里,我需要再次访问请求表单以提取用户名并处理身份验证失败的尝试,并且出现以下异常

java.io.IOException: Stream closed
Run Code Online (Sandbox Code Playgroud)

这是因为在attemptsAuthentication方法内,请求输入流被读取并显然已关闭。

如何访问unsuccessfulAuthentication中的请求正文信息?

我尝试了 SecurityContextHolder.getContext().getAuthentication() 但由于身份验证失败,它为空。

有人有什么主意吗?

此致

mps*_*tos 6

在遵循M.Deinum建议后,我能够创建一个侦听特定异常的组件:

@Component
public class AuthenticationEventListener implements ApplicationListener<ApplicationEvent> {
    private static Logger logger = Logger.getLogger(AuthenticationEventListener.class);

    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        logger.info(String.format("Event types: %s", applicationEvent.getClass()));
        if (applicationEvent instanceof AbstractAuthenticationFailureEvent) {
            String username = ((AbstractAuthenticationFailureEvent) applicationEvent).getAuthentication().getName();
            if (applicationEvent instanceof AuthenticationFailureBadCredentialsEvent) {
                logger.info(String.format("User %s failed to login", username));
                //this.handleFailureEvent(username, event.getTimestamp());
            }
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

此方法使用异常来驱动在特定场景中执行的操作。我能够像这样使用JWTAuthenticationFilter实现类似的效果

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        try {
            UserDto credentials = new ObjectMapper().readValue((request.getInputStream()), UserDto.class);
            try {
                return authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                        credentials.getUserName(),
                        credentials.getPassword(),
                        new ArrayList<>())
                );
            } catch (BadCredentialsException bce) {
                try {
                    handleBadCredentials(credentials, response);
                    throw bce;
                } catch (LockedException le) {
                    handleUserLocked(credentials, response);
                    throw le;
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        logger.info("Authentication failed");

        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType(MediaType.TEXT_PLAIN_VALUE);
        response.getWriter().print(authException.getLocalizedMessage());
        response.getWriter().flush();
    }
Run Code Online (Sandbox Code Playgroud)

感谢大家的时间和帮助,非常感谢。