在使用 Spring Security Oauth2 登录和鉴权失败时,默认返回的异常信息如下:
{
"error" : "unauthorized" ,
"error_description" : "Full authentication is required to access this resource"
}
这与我们返回的信息格式不一致。如果需要修改这种返回的格式,需要重写相关异常处理类。这里我统一的是资源服务器(网关)的响应格式。
1.无效异常Token类重写
AuthExceptionEntryPoint.java
资源服务器和Zuul都要放,和配置
@Component
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence ( HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws ServletException {
Map< String, Object> map = new HashMap < String, Object> ( ) ;
Throwable cause = authException. getCause ( ) ;
response. setStatus ( HttpStatus. OK. value ( ) ) ;
response. setHeader ( "Content-Type" , "application/json;charset=UTF-8" ) ;
Result result = null;
try {
if ( cause instanceof InvalidTokenException ) {
result = new Result ( - 1 , "认证失败,无效或过期token" ) ;
} else {
result = new Result ( - 1 , "认证失败,没有携带token" ) ;
}
response. getWriter ( ) . write ( new ObjectMapper ( ) . writeValueAsString ( result) ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
}
Zuul和资源服务器的配置ResourceServerConfig
@Autowired
private AuthExceptionEntryPoint authExceptionEntryPoint;
@Override
public void configure ( ResourceServerSecurityConfigurer resources) throws Exception {
resources
. tokenStore ( tokenStore)
. resourceId ( RESOURCE_ID)
. authenticationEntryPoint ( authExceptionEntryPoint)
. stateless ( true ) ;
}
2.权限不足类重写
CustomAccessDeniedHandler.java
只用配置资源服务器
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle ( HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException)
throws IOException, ServletException {
response. setStatus ( HttpStatus. OK. value ( ) ) ;
response. setHeader ( "Content-Type" , "application/json;charset=UTF-8" ) ;
try {
Result result = new Result ( - 1 , "权限不足" ) ;
response. getWriter ( ) . write ( new ObjectMapper ( ) . writeValueAsString ( result) ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
}
资源服务器安全配置
@Autowired
private AuthExceptionEntryPoint authExceptionEntryPoint;
@Autowired
private CustomAccessDeniedHandler customAccessDeniedHandler;
@Override
public void configure ( ResourceServerSecurityConfigurer resources) throws Exception {
resources
. tokenStore ( tokenStore)
. authenticationEntryPoint ( authExceptionEntryPoint)
. accessDeniedHandler ( customAccessDeniedHandler)
. resourceId ( RESOURCE_ID)
. stateless ( true ) ;
}