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) 问题整理的更多相关文章

  1. Spring Security OAuth2 授权码模式

     背景: 由于业务实现中涉及到接入第三方系统(app接入有赞商城等),所以涉及到第三方系统需要获取用户信息(用户手机号.姓名等),为了保证用户信息的安全和接入方式的统一, 采用Oauth2四种模式之一 ...

  2. Spring Security OAuth2 微服务认证中心自定义授权模式扩展以及常见登录认证场景下的应用实战

    一. 前言 [APP 移动端]Spring Security OAuth2 手机短信验证码模式 [微信小程序]Spring Security OAuth2 微信授权模式 [管理系统]Spring Se ...

  3. Spring Security OAuth2 Demo —— 隐式授权模式(Implicit)

    本文可以转载,但请注明出处https://www.cnblogs.com/hellxz/p/oauth2_impilit_pattern.html 写在前面 在文章OAuth 2.0 概念及授权流程梳 ...

  4. Spring Security OAuth2.0认证授权四:分布式系统认证授权

    Spring Security OAuth2.0认证授权系列文章 Spring Security OAuth2.0认证授权一:框架搭建和认证测试 Spring Security OAuth2.0认证授 ...

  5. 【Spring Cloud & Alibaba 实战 | 总结篇】Spring Cloud Gateway + Spring Security OAuth2 + JWT 实现微服务统一认证授权和鉴权

    一. 前言 hi,大家好~ 好久没更文了,期间主要致力于项目的功能升级和问题修复中,经过一年时间的打磨,[有来]终于迎来v2.0版本,相较于v1.x版本主要完善了OAuth2认证授权.鉴权的逻辑,结合 ...

  6. springboot+spring security +oauth2.0 demo搭建(password模式)(认证授权端与资源服务端分离的形式)

    项目security_simple(认证授权项目) 1.新建springboot项目 这儿选择springboot版本我选择的是2.0.6 点击finish后完成项目的创建 2.引入maven依赖  ...

  7. 转 - spring security oauth2 password授权模式

    原贴地址: https://segmentfault.com/a/1190000012260914#articleHeader6 序 前面的一篇文章讲了spring security oauth2的c ...

  8. Spring Cloud实战 | 最终篇:Spring Cloud Gateway+Spring Security OAuth2集成统一认证授权平台下实现注销使JWT失效方案

    一. 前言 在上一篇文章介绍 youlai-mall 项目中,通过整合Spring Cloud Gateway.Spring Security OAuth2.JWT等技术实现了微服务下统一认证授权平台 ...

  9. Spring Security OAuth2.0认证授权二:搭建资源服务

    在上一篇文章[Spring Security OAuth2.0认证授权一:框架搭建和认证测试](https://www.cnblogs.com/kuangdaoyizhimei/p/14250374. ...

随机推荐

  1. MAC里“微软雅黑”字体标准体和粗体无法同时使用问题的解决方法

    微软雅黑字体,有标准体和粗体两种字体,我用的系统是OSX10.9,adobe或者是office软件中,均无法同时使用.要么只能用标准体,粗体报错:要么就是能用粗体,标准体无法使用.很偶然找到了以下MA ...

  2. VS2015 经常不出现智能提示,代码颜色也没有了

    重置下.开始菜单 -->所有程序-->Visual Studio 文件夹 --> Visual Studio Tools --> Developer Command Promp ...

  3. 如何在mysql下实现事务的提交与回滚

    最近要对数据库的数据进行一个定时迁移,为了防止在执行过程sql语句因为某些原因报错而导致数据转移混乱,因此要对我们的脚本加以事务进行控制. 首先我们建一张tran_test表 CREATE TABLE ...

  4. PHP下用Memcache 实现消息队列

    Memcache 一般用于缓存服务.但是很多时候,比如一个消息广播系统,需要一个消息队列.直接从数据库取消息,负载往往不行.如果将整个消息队列用一个key缓存到memcache里面, 对于一个很大的消 ...

  5. log4j使用示例

    ### set log levels ### log4j.rootLogger = INFO , D #INFO , C , D , E ### console ### #log4j.appender ...

  6. unity调用系统剪切板功能

    package com.game.utils; import android.app.Activity; import android.content.ClipData; import android ...

  7. vncviewer鼠标不同步问题

    sh-4.1# virsh edit win7 把下面的参数: <input type='mouse' bus='ps2'/> 改成: <input type='tablet' bu ...

  8. JAVA工具类 UUID

    UUID:通用惟一识别:Universally Unique Identifier: 在一台机器上生成的数字,它保证对在同一时空中的所有机器都是唯一的. GUID是一个128位长的数字,一般用16进制 ...

  9. makefile之findstring函数

    #$(findstring <find>,<in> ) #功能:在字串<in>中查找<find>字串. #返回:如果找到,那么返回<find> ...

  10. codeForces 574b Bear and Three Musketeers

    一种巧妙到暴力方式,这题到抽象化:在一个无向图中,找一个度数和最小到三阶到圈. 首先对边进行枚举,这样确定了两个顶点,然后在对点进行枚举,找到一个可以构成三元圈到点,则计算他们到度数和. 最后保存最小 ...