Spring Cloud:Security OAuth2 自定义异常响应

1|0默认异常响应

在使用Spring Security Oauth2 登录和鉴权失败时,默认返回的异常信息如下:

{ "error": "unauthorized", "error_description": "Full authentication is required to access this resource" }

这与我们返回的信息格式不一致。如果需要修改这种返回的格式,需要重写相关异常处理类。这里我统一的是资源服务器(网关)的响应格式。

2|0自定义异常

2|1无效token异常类重写

新增 AuthExceptionEntryPoint.java

@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"); try { if(cause instanceof InvalidTokenException) { response.getWriter().write(ResultJsonUtil.build( ResponseCodeConstant.REQUEST_FAILED, ResponseStatusCodeConstant.OAUTH_TOKEN_FAILURE, ResponseMessageConstant.OAUTH_TOKEN_ILLEGAL )); }else{ response.getWriter().write(ResultJsonUtil.build( ResponseCodeConstant.REQUEST_FAILED, ResponseStatusCodeConstant.OAUTH_TOKEN_MISSING, ResponseMessageConstant.OAUTH_TOKEN_MISSING )); } } catch (IOException e) { e.printStackTrace(); } } }

2|2权限不足异常类重写

新增 CustomAccessDeniedHandler.java

@Component("customAccessDeniedHandler") 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 { response.getWriter().write(ResultJsonUtil.build( ResponseCodeConstant.REQUEST_FAILED, ResponseStatusCodeConstant.OAUTH_TOKEN_DENIED, ResponseMessageConstant.OAUTH_TOKEN_DENIED )); } catch (IOException e) { e.printStackTrace(); } } }

2|3资源配置类中设置异常处理类

修改资源配置类 ResourceServerConfiguration.java

@Override public void configure(ResourceServerSecurityConfigurer resources) { resources.tokenExtractor(customTokenExtractor); resources.authenticationEntryPoint(authExceptionEntryPoint) .accessDeniedHandler(customAccessDeniedHandler); }

示例代码:https://github.com/BNDong/spring-cloud-examples/tree/master/spring-cloud-zuul/cloud-zuul


__EOF__

本文作者BNDong
本文链接https://www.cnblogs.com/bndong/p/10275430.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   fortuneju  阅读(1451)  评论(1编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示