Регистрировать информацию о пользователе при неудачной попытке - PullRequest
0 голосов
/ 19 июня 2020

Я хочу иметь доступ к своим данным пользователя при сбое входа в систему, чтобы я мог подсчитать количество неудачных попыток пользователя. Как я могу получить доступ к пользовательской информации и сохранить ее в моей базе данных в случае сбоя? Я где-то читал, что AuthenticationFailureHandler может быть решением этой проблемы, но из того, что я вижу, он работает только с formLogin?

У меня есть конечная точка входа

@CrossOrigin
@RequestMapping(value = "/signin", method = RequestMethod.POST)
@ApiOperation(value = "Sign in endpoint", notes = "You have to provide a valid login request")
public ResponseEntity<?> authenticateUser(@ApiParam(value = "The login request", required = true)
                                          @Valid @RequestBody LoginRequest loginRequest) {

    Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));

    UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();

    // Set authentication so that when /authenticate, we can retrieve the authenticated user

   . . .

Это моя точка аутентификации jwt при сбое аутентификации.

@Component
public class AuthEntryPointJwt implements AuthenticationEntryPoint {

    private static final Logger logger = LoggerFactory.getLogger(AuthEntryPointJwt.class);

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {
        logger.info("> AuthEntryPointJwt");
        logger.error("Unauthorized error: {}", authException.getMessage());
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Error: Unauthorized");
    }
}

Это моя веб-безопасность

   @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

        private static final Logger LOGGER = LoggerFactory.getLogger(WebSecurityConfig.class);

        @Autowired
        UserDetailsServiceImpl userDetailsService;

        @Autowired
        private AuthEntryPointJwt unauthorizedHandler;

        @Bean
        public AuthTokenFilter authenticationJwtTokenFilter() {
            LOGGER.info("> AuthenticationManagerBuilder authenticationJwtTokenFilter");
            return new AuthTokenFilter();
        }

        @Override
        public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
            LOGGER.info("> AuthenticationManagerBuilder authenticationManagerBuilder");
            authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
        }

        @Bean
        @Override
        public AuthenticationManager authenticationManagerBean() throws Exception {
            LOGGER.info("> AuthenticationManagerBuilder authenticationManagerBean");
            return super.authenticationManagerBean();
        }

        @Bean
        public PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.cors().and().csrf().disable()
                    .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                    .authorizeRequests()
                    .antMatchers("/test/**").authenticated()
                    .antMatchers("/signup").hasAuthority("SUPER_ADMIN");

            http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        }

        @Bean
        public CorsConfigurationSource corsConfigurationSource() {
            final CorsConfiguration configuration = new CorsConfiguration();
            configuration.setAllowedOrigins(Arrays.asList("*"));
            configuration.setAllowedMethods(Arrays.asList("HEAD",
                    "GET", "POST", "PUT", "DELETE", "PATCH"));
            configuration.setAllowCredentials(true);
            configuration.setAllowedHeaders(Arrays.asList("*"));
            final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            source.registerCorsConfiguration("/**", configuration);
            return source;
        }
    }

1 Ответ

0 голосов
/ 20 июня 2020

Да. AuthenticationFailureHandler будет вызываться только в том случае, если вы настроите фильтр для аутентификации, расширив AbstractAuthenticationProcessingFilter, как это делает formLogin.

Но похоже, что теперь вы реализуете индивидуальный способ аутентификации с использованием spring-mvc-rest, и вы можете выполните следующее, что эквивалентно тому, что делает AbstractAuthenticationProcessingFilter для вызова AuthenticationFailureHandler:

@RestController
public void AuthenticateController {

    @Autowired AuthenticationFailureHandler failureHandler;

    @RequestMapping(value = "/signin", method = RequestMethod.POST)
    public ResponseEntity<?> authenticateUser(LoginRequest loginRequest, HttpServletRequest request, HttpServletResponse response) {

        try {
            Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
        }catch (AuthenticationException failed) {
          failureHandler.onAuthenticationFailure(request, response, failed);
        }
    }
}

PS Поскольку вы настраиваете аутентификацию с помощью spring- mvc -rest, а не следуйте инфраструктуре безопасности Spring чтобы реализовать его на основе фильтра сервлетов, я предполагаю, что вам также необходимо настроить безопасность Spring, чтобы полностью игнорировать AuthenticateController, и никакая другая функция безопасности Spring не будет применяться к нему. Обычно я буду следить за инфраструктурой безопасности Spring, которая настраивает процесс аутентификации на основе фильтра сервлетов, поскольку он более совместим с экосистемой безопасности Spring.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...