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

时间:2019-01-21 17:41:51

标签: spring spring-security

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

HttpSecurity配置

@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);

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

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);
    }
}

登录正常,没有问题。我的问题出在 unsuccessfulAuthentication 方法上。当用户输入错误的凭据时,会引发BadCredentials异常,并调用 unsuccessfulAuthentication 方法。在这里,我需要再次访问请求表以提取用户名并处理身份验证失败的尝试,并且我遇到了以下异常

java.io.IOException: Stream closed

这是因为在 attemptAuthentication 方法内部,请求输入流被读取并明显关闭。

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

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

有人有什么主意吗?

最好的问候

1 个答案:

答案 0 :(得分:0)

在遵循 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());
            }
        }

    }
}

此方法使用异常来驱动特定情况下的操作。我可以像这样使用 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();
    }

非常感谢您的时间和帮助,