如何在 Spring Security 中自定义“错误凭据”错误响应?
Posted
技术标签:
【中文标题】如何在 Spring Security 中自定义“错误凭据”错误响应?【英文标题】:How to Customize "Bad credentials" error response in Spring Security? 【发布时间】:2020-10-03 19:47:33 【问题描述】:我正在使用 Spring-cloud-oauth2 创建授权服务器。它基于客户端凭据以及用户名和密码。我的问题是,在输入错误的用户名密码时,我无法自定义错误凭据的错误响应。我通过实现 AuthenticationEntryPoint 接口控制了错误客户端凭据的错误响应。与我绑定处理错误凭据响应的方法类似,使用AuthenticationFailureHandler
并关注Baeldung tutorial。但似乎失败处理程序没有被注册,所以onAuthenticationFailure
方法永远不会被执行。我想要实现的正是这个question 的解决方案。
以下是部分相关代码:
@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
【问题讨论】:
检查解决方案是否适合您***.com/questions/62368896/… 对不起,这似乎不起作用@S 您是否尝试过从配置中删除`.failureHandler(customAuthenticationFailureHandler)`,然后运行上一条评论中提到的解决方案? 我现在试过了。但是,我仍然无法做到。你知道一些过滤器实际上给出了这个原始响应吗? 【参考方案1】:您可以尝试创建一个扩展 OAuth2Exception 的 CustomOauthException,如此链接 medium blog for customising oauth response 中所述。然后您可以使用自定义 JsonSerializer 自定义 CustomOauthException 给出的响应。
这是实现相同用例的另一种方法。虽然我不知道为什么
onAuthenticationFailure
没有在给定的代码中执行。
希望这会有所帮助。
【讨论】:
以上是关于如何在 Spring Security 中自定义“错误凭据”错误响应?的主要内容,如果未能解决你的问题,请参考以下文章
使用 AuthenticationFailureHandler 在 Spring Security 中自定义身份验证失败响应