首先在资源服务中配置一个自定义OAuth2身份验证入口点
@Component
public class CustomOAuth2AuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
response.setContentType("application/json;charset=UTF-8");
// 设置响应状态码为 401 Unauthorized
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
// 将业务异常转换为自定义的错误响应
Result<Object> failed = Result.failed(ResultCode.INVALID_TOKEN);
// 将错误响应转换为 JSON 并写入响应体
ObjectMapper objectMapper = new ObjectMapper();
response.getWriter().write(objectMapper.writeValueAsString(failed));
}
}
然后在ResourceConfig重写configure(ResourceServerSecurityConfigurer resources)方法
@Autowired
private CustomOAuth2AuthenticationEntryPoint customOAuth2AuthenticationEntryPoint;
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.authenticationEntryPoint(customOAuth2AuthenticationEntryPoint);
}