Spring Security 用户名密码AuthenticationFilter : How to access Request after a failed login

标签 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);

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

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。

有人知道吗?

最好的问候

最佳答案

关注之后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();
    }

感谢大家抽出宝贵时间提供帮助,非常感谢。

关于Spring Security 用户名密码AuthenticationFilter : How to access Request after a failed login,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54295230/

相关文章:

java - 专家! Spring Boot 在依赖项目中提到了错误的依赖版本

java - 在 JSP 中链接不同的页面并保留当前的 ​​Spring Security session

grails - Grails Spring Security Core-手动生成密码

使用 WebSockets 的 Spring Security - 禁止 403

java - Spring @Controller 和 Transactionmanager

java - Spring data + hibernate 使用了错误的列名

java - 如何使 Spring 缓存中的条目每小时失效?

java - 为什么 spring security 注销不起作用?

java - 为什么 Spring Security 不起作用?

oauth - 使用 OAuth2 下载 Javascript 文件