如何处理springboot中基本身份验证的成功和失败?

问题描述 投票:0回答:1

我需要添加一些自定义逻辑,例如使用服务来记录我的失败尝试或在成功登录时重置我的失败尝试。如何使用 httpBasic 执行此操作?所以我需要 httpBasic() 的失败处理程序和成功处理程序。

目前我正在尝试添加这样的自定义过滤器

Spring 安全配置

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig {
    @Autowired
    @Qualifier("customAuthenticationEntryPoint")
    AuthenticationEntryPoint authEntryPoint;

    @Autowired
    @Qualifier("customBasicAuthFilter")
    BasicAuthenticationFilter customBasicAuthFilter;

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE + 5)
    public SecurityFilterChain initSetupSecurityFilterChain(HttpSecurity http) throws Exception {

        http
                .securityMatcher(AntPathRequestMatcher.antMatcher("/init-setup/**"))
                .authorizeHttpRequests(authorizeRequests  ->
                        authorizeRequests
                                .requestMatchers(HttpMethod.POST, "/init-setup/otp").permitAll()
                                .requestMatchers(HttpMethod.GET, "/init-setup/default-client-credentials").authenticated()
                                .anyRequest().authenticated()
                )
                .csrf(AbstractHttpConfigurer::disable)
                .sessionManagement(sessionManagement ->
                        sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
//                .httpBasic(basic -> basic.authenticationEntryPoint(authEntryPoint)) // custom authentication entry point
                .addFilterAt(customBasicAuthFilter, BasicAuthenticationFilter.class)
                .exceptionHandling(Customizer.withDefaults());
        return http.build();
    }
}

自定义基本验证过滤器

@Component("customAuthenticationFilter")
public class CustomBasicAuthFilter extends BasicAuthenticationFilter {

    @Autowired
    public CustomBasicAuthFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
                                              Authentication authResult) throws IOException {
        System.out.println("SUCCESS::");
    }

    protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
                                                AuthenticationException failed) throws IOException {
        System.out.println("FAILS::");
    }

}

应用程序未启动并抛出此错误

Parameter 0 of constructor in com.shabodi.laas.config.CustomBasicAuthFilter required a bean of type 'org.springframework.security.authentication.AuthenticationManager' that could not be found.

Consider defining a bean of type 'org.springframework.security.authentication.AuthenticationManager' in your configuration.
java spring spring-boot spring-security basic-authentication
1个回答
0
投票

尝试将这 2 个注释添加到 CustomBasicAuthFilter 类中。

enter image description here

希望有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.