如何在 Spring 安全性中自定义 "Bad credentials" 错误响应?

How to Customize "Bad credentials" error response in Spring Security?

我正在使用 Spring-cloud-oauth2 创建授权服务器。它基于客户端凭据以及用户名和密码。我的问题是,当输入不正确的用户名密码时,我无法自定义错误凭据的错误响应。我通过实现 AuthenticationEntryPoint 接口控制错误客户端凭据的错误响应。类似于我绑定处理错误凭证响应,使用 AuthenticationFailureHandler 跟随 Baeldung tutorial. But it seems like failure handler is not getting registered and so onAuthenticationFailure method is never getting executed. What I am trying to achieve is a solution for exactly this .

部分相关代码如下:

@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {

    Logger logger=LoggerFactory.getLogger(CustomAuthenticationFailureHandler.class);

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {

        httpServletResponse.setStatus(HttpStatus.BAD_REQUEST.value());

        Map<String, Object> data = new HashMap<>();
        data.put("timestamp", new Date());
        data.put("exception", e.getMessage());

        httpServletResponse.getOutputStream().println(objectMapper.writeValueAsString(data));

    }
}
// CustomAuthenticationFailureHandler.Class

以下是我的 WebSecurityConfigurerAdapter:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService customUserDetailsService;

    @Autowired
    private AuthenticationProvider customAuthenticationProvider;

    @Autowired
    AuthenticationEntryPoint customAuthenticationEntryPoint;

    @Autowired
    private CustomAuthenticationFailureHandler customAuthenticationFailureHandler;



    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(customAuthenticationProvider);
        // auth.userDetailsService(customUserDetailsService).passwordEncoder(encoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/jwks-json")
                .permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .failureHandler(customAuthenticationFailureHandler)
                .and()
                .httpBasic().
                and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.NEVER);

        http.exceptionHandling().authenticationEntryPoint(customAuthenticationEntryPoint);

        //http.addFilterAfter(customExceptionTranslation(),ExceptionTranslationFilter.class);


    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public PasswordEncoder encoder(){



        PasswordEncoder defaultEncoder = new BCryptPasswordEncoder();

        Map<String, PasswordEncoder> encoders = new HashMap<>();
        encoders.put("noop", NoOpPasswordEncoder.getInstance());
        encoders.put("bcrypt", new BCryptPasswordEncoder());

        DelegatingPasswordEncoder passworEncoder = new DelegatingPasswordEncoder(
                "bcrypt", encoders);

        passworEncoder.setDefaultPasswordEncoderForMatches(defaultEncoder);

        return passworEncoder;
    }

请告诉我哪里做错了。提前致谢

ng-security-custom-authentication-failure-handler

您可以尝试创建一个扩展 OAuth2Exception 的 CustomOauthException,如 link medium blog for customising oauth response 中所述。然后您可以使用自定义 JsonSerializer 自定义 CustomOauthException 给出的响应。

这是实现相同用途的另一种方法case.Though我不知道为什么 onAuthenticationFailure 未在给定代码中执行。

希望对您有所帮助。