Spring Security OAuth2 授权失败(401) 问题整理
Spring Cloud架构中采用Spring Security OAuth2作为权限控制,关于OAuth2详细介绍可以参考 http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html
项目中采用OAuth2四种模式中的两种,Password模式和Client模式, Password模式用于控制用户的登录,Client模式用于控制后端服务相互调用。
权限架构调整后在近期发现一些问题,由于网上资料不多,只能单步调试方式看源码 (其实带着问题看源码是最好的方式)。现在将问题和解决方案整理如下:
一、免登录接口校验token问题
问题:APP端反馈,一些免登录接口会校验token
详细:经过测试发现,免登录接口 如果传了access_token会对token合法性就行校验,如果不传接口不会校验,这导致了免登录接口的过期token会报错
排查:经过查看源码发现spring-security-oauth2的过滤器 OAuth2AuthenticationProcessingFilter 会对请求进行拦截,(具体源码就不截图了)
- 如果存在access_token 则会根据userInfoEndpointUrl去认证服务器上校验token信息,
- 如果不存在access_token 则会继续执行spring-security的拦截器FilterSecurityInterceptor。 FilterSecurityInterceptor对路径是否需要授权,已经授权是否通过做校验~
解决: 可以采用过滤器在执行到核心过滤器OAuth2AuthenticationProcessingFilter ,将不需要授权的请求头中的access_token过滤掉。或者APP免登录接口不传token
最终采用的是后者
二、Token失效返回的是状态401的错误
1、问题: APP端反馈,传递失效access_token,返回401状态,期望是200同时以错误码方式提示token失效。
排查:经过单步调试分析源码发现,token失效后,认证服务器会抛出异常,同时响应给资源服务器,资源服务发现认证服务器的错误后会抛出InvalideException。
抛出的异常会经过默认的DefaultWebResponseExceptionTranslator 处理然后 Reseponse给Client端。
解决:通过上面的分析指导。最后的异常是在DefaultWebResponseExceptionTranslator 处理的,所以只需要
- 自定义实现类Implements WebResponseExceptionTranslator 接口处理异常装换逻辑,
- 使得自定义的类生效
(1)自定义异常转换类
@Slf4j
public class Auth2ResponseExceptionTranslator implements WebResponseExceptionTranslator { @Override
public ResponseEntity<OAuth2Exception> translate(Exception e) {
log.error("Auth2异常", e);
Throwable throwable = e.getCause();
if (throwable instanceof InvalidTokenException) {
log.info("token失效:{}", throwable);
return new ResponseEntity(new Message<>(ServerConstant.INVALID_TOKEN.getMsg(), ServerConstant.INVALID_TOKEN.getCode()), HttpStatus.OK);
}
return new ResponseEntity(new Message(e.getMessage(), String.valueOf(HttpStatus.METHOD_NOT_ALLOWED.value())), HttpStatus.METHOD_NOT_ALLOWED);
}
}
(2)资源服务器中使得自定义类生效
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
// 定义异常转换类生效
AuthenticationEntryPoint authenticationEntryPoint = new OAuth2AuthenticationEntryPoint();
((OAuth2AuthenticationEntryPoint) authenticationEntryPoint).setExceptionTranslator(new Auth2ResponseExceptionTranslator());
resources.authenticationEntryPoint(authenticationEntryPoint);
} @Override
public void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.exceptionHandling()
// 定义的不存在access_token时候响应
.authenticationEntryPoint(new SecurityAuthenticationEntryPoint())
.and()
.authorizeRequests().antMatchers("/**/**").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic().disable();
}
2、问题:测试发现授权接口,当请求参数中不存在access_token时发现接口返回错误信息:
{"timestamp":1539337154336,"status":401,"error":"Unauthorized","message":"No message available","path":"/app/businessCode/list"}
排查:经过前面的分析发现,上面提到Security的FilterSecurityInterceptor对OAuth2中返回的信息和本身配置校验后,抛出AccessDenyException。
解决:经过上面的几个问题的处理,发现思路还是一样的,需要定义响应结果,
即1、自定义响应处理逻辑SecurityAuthenticationEntryPoint 2、自定义处理逻辑SecurityAuthenticationEntryPoint生效(见上面的配置)
SecurityAuthenticationEntryPoint具体实现:
@Slf4j
public class SecurityAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
log.error("Spring Securtiy异常", authException);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter out = response.getWriter();
out.print(JSON.toJSONString(new Message<>(ServerConstant.INVALID_TOKEN.getMsg(), ServerConstant.INVALID_TOKEN.getCode())));
}
}
Spring Security OAuth2 授权失败(401) 问题整理的更多相关文章
- Spring Security OAuth2 授权码模式
背景: 由于业务实现中涉及到接入第三方系统(app接入有赞商城等),所以涉及到第三方系统需要获取用户信息(用户手机号.姓名等),为了保证用户信息的安全和接入方式的统一, 采用Oauth2四种模式之一 ...
- Spring Security OAuth2 微服务认证中心自定义授权模式扩展以及常见登录认证场景下的应用实战
一. 前言 [APP 移动端]Spring Security OAuth2 手机短信验证码模式 [微信小程序]Spring Security OAuth2 微信授权模式 [管理系统]Spring Se ...
- Spring Security OAuth2 Demo —— 隐式授权模式(Implicit)
本文可以转载,但请注明出处https://www.cnblogs.com/hellxz/p/oauth2_impilit_pattern.html 写在前面 在文章OAuth 2.0 概念及授权流程梳 ...
- Spring Security OAuth2.0认证授权四:分布式系统认证授权
Spring Security OAuth2.0认证授权系列文章 Spring Security OAuth2.0认证授权一:框架搭建和认证测试 Spring Security OAuth2.0认证授 ...
- 【Spring Cloud & Alibaba 实战 | 总结篇】Spring Cloud Gateway + Spring Security OAuth2 + JWT 实现微服务统一认证授权和鉴权
一. 前言 hi,大家好~ 好久没更文了,期间主要致力于项目的功能升级和问题修复中,经过一年时间的打磨,[有来]终于迎来v2.0版本,相较于v1.x版本主要完善了OAuth2认证授权.鉴权的逻辑,结合 ...
- springboot+spring security +oauth2.0 demo搭建(password模式)(认证授权端与资源服务端分离的形式)
项目security_simple(认证授权项目) 1.新建springboot项目 这儿选择springboot版本我选择的是2.0.6 点击finish后完成项目的创建 2.引入maven依赖 ...
- 转 - spring security oauth2 password授权模式
原贴地址: https://segmentfault.com/a/1190000012260914#articleHeader6 序 前面的一篇文章讲了spring security oauth2的c ...
- Spring Cloud实战 | 最终篇:Spring Cloud Gateway+Spring Security OAuth2集成统一认证授权平台下实现注销使JWT失效方案
一. 前言 在上一篇文章介绍 youlai-mall 项目中,通过整合Spring Cloud Gateway.Spring Security OAuth2.JWT等技术实现了微服务下统一认证授权平台 ...
- Spring Security OAuth2.0认证授权二:搭建资源服务
在上一篇文章[Spring Security OAuth2.0认证授权一:框架搭建和认证测试](https://www.cnblogs.com/kuangdaoyizhimei/p/14250374. ...
随机推荐
- unity3d的三种平面坐标系
unity3d有如下三种平面坐标系: 1.屏幕坐标系 2.视口坐标系viewport 3.GUI坐标系
- iperf使用
1. sourceforge搜索iperf下载 2. ./configure make make install 3. server:iperf -s -p 12345 -i 1 -M: client ...
- unity, access standard shared emission by script
unity 5.1.1f1 personal 用下面方法在脚本中设置standard shader的emssion: gameObject.GetComponent<MeshRenderer&g ...
- wpf 帧动画
帧动画实现很简单 <ImageBrush x:Key="speed_s" Stretch="Fill" ImageSource="/images ...
- instancetype 对比 id 的好处
转自:http://blog.csdn.net/yangzychina/article/details/8818941 今天研究代码的时候,发现居然返回 instancetype 类型,很惊讶自己学识 ...
- Codeforces Round #238 (Div. 2) D. Toy Sum
D. Toy Sum time limit per test:1 second memory limit per test:256 megabytes input:standard input o ...
- poj 1636 Prison rearrangement
Prison rearrangement Time Limit: 3000MS Memory Limit: 10000K Total Submissions: 2158 Accepted: ...
- 0051 MyBatis关联映射--多对多关系
用户与订单时一对多关系,再加上商品信息的话,订单与商品之间就是多对多关系了 DROP DATABASE IF EXISTS testdb; USE testdb; /*用户表,记录用户信息:用户与订单 ...
- CefSharp 集成谷歌浏览器详解---(一)环境搭建(没测试过,不知道好不好用)
https://blog.csdn.net/zpyxman/article/details/78538808
- JavaScript中的对象冒充
JavaScript里没有继承关键字,想要继承一个类需要用到“对象冒充”. <!DOCTYPE html> <html xmlns="http://www.w3.org/1 ...