【发布时间】:2017-08-07 23:19:09
【问题描述】:
目前,每当用户身份验证失败时,spring security 都会响应:
{"error": "invalid_grant","error_description": "Bad credentials"}
我想使用如下响应代码来增强此响应:
{"responsecode": "XYZ","error": "invalid_grant","error_description": "Bad credentials"}
经过一番摸索,看起来我需要做的是实现一个AuthenticationFailureHandler,我已经开始这样做了。但是,每当我提交无效的登录凭据时,似乎永远无法达到 onAuthenticationFailure 方法。我已经单步执行了代码,并在 onAuthenticationFailure 方法中进行了登录,以确认它没有被访问。
我的失败处理程序是:
@Component
public class SSOAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler{
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
super.onAuthenticationFailure(request, response, exception);
response.addHeader("responsecode", "XYZ");
}
}
我的 WebSecurityConfigurerAdapter 包含:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired SSOAuthenticationFailureHandler authenticationFailureHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.formLogin().failureHandler(authenticationFailureHandler);
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(service).passwordEncoder(passwordEncoder());
auth.authenticationEventPublisher(defaultAuthenticationEventPublisher());
}
@Bean
public DefaultAuthenticationEventPublisher defaultAuthenticationEventPublisher(){
return new DefaultAuthenticationEventPublisher();
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public SSOAuthenticationFailureHandler authenticationHandlerBean() {
return new SSOAuthenticationFailureHandler();
}
@Bean
public PasswordEncoder passwordEncoder(){
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
}
我的问题是:
- 这是实现我想要的结果的正确方法吗? (自定义spring安全认证响应)
- 如果是这样,我在尝试设置身份验证失败处理程序时是否做错了什么(因为错误的登录似乎没有到达 onAuthenticationFailure 方法?
谢谢!
【问题讨论】:
-
你可以在你的配置方法中添加异常处理 http.csrf().disable().exceptionHandling().authentcationEntryPoint(unauthorizedHanlderHere);您必须创建一个实现 AuthencationEntryPoint 的类。
标签: java spring authentication spring-security