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. ...
随机推荐
- 在SQL Server中调用.NET程序集
需求是这样的,我在.net程序里操作数据时将一些字段数据加密了,这些数据是很多系统共用的,其中一delphi程序也需要用到,并且需要将数据解密,由于我在.net里加密的方式比较特殊,在delphi程序 ...
- https://github.com/CocoaPods/CocoaPods/search?q=No+such+file+or+directory报错解决方式
――― MARKDOWN TEMPLATE ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― ### Command ``` /U ...
- FreeSWITCH小结:呼叫的发起与跟踪
需求描述 虽然现有的FreeSWITCH功能已经很强大,但是很多情况下,为了配合业务上的功能,还需要做一些定制开发. 有一个基本需求是:如何控制fs外呼,并跟踪外呼后的一系列状态. 解决方案 下面我就 ...
- spine findBone
spBone* bone=skeletonAnimationNode->findBone("boneName"); CCPoint boneWorldPos=ccp(bone ...
- atitit.html5动画特效----打水漂 ducks_and_drakes
atitit.html5动画特效----打水漂 ducks_and_drakes 1. 原理 1 2. fly jquery插件 1 3. ---------code 2 4. 参考 4 1. 原理 ...
- redis命令_SETNX
SETNX key value 将 key 的值设为 value ,当且仅当 key 不存在. 若给定的 key 已经存在,则 SETNX 不做任何动作. SETNX 是『SET if Not eXi ...
- 如何改变iframe滚动条的样式?
如何改变iframe滚动条的样式? web前端开发 css javascript iframe html RayLiao 2014年11月19日提问 · 2014年11月20日更新 关注 关注 收藏 ...
- 怎么来爬取代理服务器ip地址?
一年前突然有个灵感,想搞个强大的网盘搜索引擎,但由于大学本科学习软件工程偏嵌入式方向,web方面的能力有点弱,不会jsp,不懂html,好久没有玩过sql,但就是趁着年轻人的这股不妥协的劲儿,硬是把以 ...
- STM32F10x_RTC秒中断
Ⅰ.概述 RTC(Real Time Clock)是实时时钟的意思,它其实和TIM有点类似,也是利用计数的原理,选择RTC时钟源,再进行分频,到达计数的目的. 该文主要讲述关于RTC的秒中断功能,这个 ...
- 经典Mathematica函数大全
转自:http://blog.renren.com/share/238323208/8426343822 Mathmatic 函数表 一.运算符及特殊符号 Line1; 执行Line,不显示结果 ...