对于客户端开发或者网站开发而言,调用接口返回有统一的响应体,可以针对性的设计界面,代码结构更加清晰,层次也更加分明。

默认异常响应

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

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

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

自定义异常响应

无效 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();
}
}
}

权限不足异常类重写

新增 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();
}
}
}

资源配置类中设置异常处理类

修改资源配置类 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

Spring Cloud:Security OAuth2 自定义异常响应的更多相关文章

  1. 使用Spring Cloud Security OAuth2搭建授权服务

    阅读数:84139 前言: 本文意在抛砖引玉,帮大家将基本的环境搭起来,具体实战方案还要根据自己的业务需求进行制定.我们最终没有使用Spring Security OAuth2来搭建授权服务,而是完全 ...

  2. Spring Cloud Security OAuth2.0 认证授权系列(一) 基础概念

    世界上最快的捷径,就是脚踏实地,本文已收录[架构技术专栏]关注这个喜欢分享的地方. 前序 最近想搞下基于Spring Cloud的认证授权平台,总体想法是可以对服务间授权,想做一个基于Agent 的无 ...

  3. Spring Boot Security Oauth2之客户端模式及密码模式实现

    Spring Boot Security Oauth2之客户端模式及密码模式实现 示例主要内容 1.多认证模式(密码模式.客户端模式) 2.token存到redis支持 3.资源保护 4.密码模式用户 ...

  4. Spring Cloud Security&Eureka安全认证(Greenwich版本)

    Spring Cloud Security&Eureka安全认证(Greenwich版本) 一·安全 Spring Cloud支持多种安全认证方式,比如OAuth等.而默认是可以直接添加spr ...

  5. 妹子始终没搞懂OAuth2.0,今天整合Spring Cloud Security 一次说明白!

    大家好,我是不才陈某~ 周二发了Spring Security 系列第一篇文章,有妹子留言说看了很多文章,始终没明白OAuth2.0,这次陈某花了两天时间,整理了OAuth2.0相关的知识,结合认证授 ...

  6. Spring Boot Security OAuth2 实现支持JWT令牌的授权服务器

    概要 之前的两篇文章,讲述了Spring Security 结合 OAuth2 .JWT 的使用,这一节要求对 OAuth2.JWT 有了解,若不清楚,先移步到下面两篇提前了解下. Spring Bo ...

  7. Spring Cloud Zuul记录接口响应数据

    系统在生产环境出现问题时,排查问题最好的方式就是查看日志了,日志的记录尽量详细,这样你才能快速定位问题. 如果需要在Zuul中进行详细的日志记录,这两种日志必不可少. API请求信息 API响应信息 ...

  8. Spring Security OAuth2 Demo -- good

    1. 添加依赖授权服务是基于Spring Security的,因此需要在项目中引入两个依赖: <dependency> <groupId>org.springframework ...

  9. Spring Security OAuth2 Demo

    Spring Security OAuth2 Demo 项目使用的是MySql存储, 需要先创建以下表结构: CREATE SCHEMA IF NOT EXISTS `alan-oauth` DEFA ...

随机推荐

  1. what a fuck!这是什么鬼东西?

    Topic Link http://ctf5.shiyanbar.com/DUTCTF/1.html 1) 打开链接发现一片看不懂的东西,还真是WTF? 2)分析发现是Jother编码 将其放到浏览器 ...

  2. Java读取Excel指定列的数据详细教程和注意事项

    本文使用jxl.jar工具类库实现读取Excel中指定列的数据. jxl.jar是通过java操作excel表格的工具类库,是由java语言开发而成的.这套API是纯Java的,并不依赖Windows ...

  3. Python3+Selenium2完整的自动化测试实现之旅(五):自动化测试框架、Python面向对象以及POM设计模型简介

    前言 之前的系列博客,陆续学习整理了自动化测试环境的搭建.IE和Chrome浏览器驱动的配置.selenium-webdriver模块封装的元素定位以及控制浏览器.处理警示框.鼠标键盘等方法的使用,这 ...

  4. 第58章 Profile Service - Identity Server 4 中文文档(v1.0.0)

    IdentityServer通常在创建令牌或处理对userinfo或内省端点的请求时需要有关用户的身份信息.默认情况下,IdentityServer仅具有身份验证cookie中的声明,以便为此身份数据 ...

  5. [转]GitLab-CI与GitLab-Runner

    本文转自:https://www.jianshu.com/p/2b43151fb92e 一.持续集成(Continuous Integration) 要了解GitLab-CI与GitLab Runne ...

  6. Bable实现由ES6转译为ES5

    Babel是一个广泛使用的转码器,可以将ES6代码转译为ES5代码,从而在现有环境下执行. 举例说明: 转译前(ES6格式)代码如下: let User = { name : '张三', age : ...

  7. PhpStorm 运行出现502 Bad Gateway

    打开PhpStorm,菜单栏File --> Settings... 一.点开Languages & Frameworks 选PHP PHP language level:选PHP版本, ...

  8. 【代码笔记】Web-CSS-CSS Padding(填充)

    一,效果图. 二,代码. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> ...

  9. JS判断类型

    JS中的typeof方法可以查看数据的类型,如下: console.log(typeof 2); // number console.log(typeof "2"); // str ...

  10. [翻译] Oracle Database 12c 新特性Multitenant

    译自官方白皮书http://www.oracle.com/technetwork/database/plug-into-cloud-wp-12c-1896100.pdf,包含新的云计算相关技术的介绍. ...