大佬教程收集整理的这篇文章主要介绍了Spring Boot REST API / Spring Security:身份验证失败时返回自定义消息,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
的httpSecurity
类有一个叫做方法exceptionHandling可用于覆盖默认行为。以下示例介绍了如何自定义响应消息。
@OverrIDe
protected voID configure(httpSecurity http) throws Exception {
http
// your custom configuration goes here
.exceptionHandling()
.authenticationEntryPoint((request, response, E) -> {
String Json = String.format("{\"message\": \"%s\"}", e.getmessage());
response.setStatus(httpServletResponse.SC_UNAUTHORIZED);
response.setContentType("application/Json");
response.setCharacterEnCoding("UTF-8");
response.getWriter().write(Json);
});
}
最初,我想到的@ControllerAdvice
是捕获整个应用程序的身份验证异常。
import org.springframework.http.httpStatus;
import org.springframework.security.core.AuthenticationException;
@ControllerAdvice
public class AuthExceptionHandler {
@ResponseStatus(httpStatuS.UNAUTHORIZED)
@ExceptionHandler(AuthenticationException.class)
@ResponseBody
public String handleAuthenticationException(AuthenticationException E) {
return String.format("{\"message\": \"%s\"}", e.getmessage());
}
}
在上面的示例中,JsON是手动构建的,但是您可以简单地返回一个POJO,该POJO将被映射到JsON中,就像从常规REST控制器中一样。既然Spring
4.3,你也可以使用@RestControllerAdvice,这是一个组合@ControllerAdvice
和@ResponseBody
。
因为在到达任何控制器之前,该异常将由抛出AbstractSecurityInterceptor
并由ExceptionTranslationFilter处理。
我有一个使用jersey作为JAX-RS实现的Spring Boot应用程序。这是我的安全配置:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = truE)
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired TokenAuthenticationProvider tokenAuthenticationProvider;
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(tokenAuthenticationProvider);
}
@Override
protected void configure(httpSecurity http) throws Exception {
http.addFilterBefore(new AuthenticationTokenFilter(),BasicAuthenticationFilter.class)
.csrf().disable()
.authorizerequests()
.antMatchers("/dataHub/**")
.authenticated();
}
}
我想要做的是有一种方法来捕获我的TokenAuthenticationProvider抛出的异常,并将其转换为我们已经同意的标准化JSON格式。有没有办法做到这一点?我尝试添加自定义AuthenticationFailureHandler,但无法正常工作。
以上是大佬教程为你收集整理的Spring Boot REST API / Spring Security:身份验证失败时返回自定义消息全部内容,希望文章能够帮你解决Spring Boot REST API / Spring Security:身份验证失败时返回自定义消息所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。