相关文章:

  1. OAuth2的定义和运行流程
  2. Spring Security OAuth实现Gitee快捷登录
  3. Spring Security OAuth实现GitHub快捷登录
  4. Spring Security的过滤器链机制
  5. Spring Security OAuth Client配置加载源码分析
  6. Spring Security内置过滤器详解
  7. 为什么加载了两个OAuth2AuthorizationRequestRedirectFilter分析
  8. Spring Security 自定义授权服务器实践

前言

在前面我们使用最小化配置的方式搭建了自己的授权服务器,现在我们依旧用最小化的方式配置自己的资源服务器。
资源服务器负责scope的鉴权、authorities的鉴权、基于用户角色的鉴权等。

最小化配置

安装资源服务器

1、 新建一个Spring Boot项目,命名为spring-security-resource-server
2、引入pom.xml依赖

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId>
</dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>

其中与授权服务器依赖不同的是,资源服务器有spring boot版本,版本号会有spring boot进行管理,不需要显示声明。

配置资源服务器

1、配置application.yml 文件

spring:security:oauth2:resourceserver:jwt:issuer-uri: http://localhost:9000

该配置用于指定授权服务器地址,资源服务器将从该地址获取JWT令牌,并根据JWT中的属性进一步自我配置,发现授权服务器的公钥、验证JWT令牌。

2、创建配置类

@EnableWebSecurity(debug = true)
public class ResoruceServerConfig {@BeanSecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {http.authorizeRequests().mvcMatchers("/userinfo/**").hasAuthority("SCOPE_userinfo").and().oauth2ResourceServer().jwt();return http.build();}}

.mvcMatchers("/userinfo/**").hasAuthority("SCOPE_userinfo")匹配/userinfo/**地址,允许访问范围是SCOPE_userinfo
oauth2ResourceServer()定义为资源服务器
jwt()使用JWT令牌

3、 创建一个资源接口
/userinfo/用来获取资源所有者基本信息

@Data
public class UserInfoRes {private String username;
}

创建Rest接口

@RestController
public class UserInfoController {@GetMapping("/userinfo")public UserInfoRes getUserInfo() {UserInfoRes userInfoRes = new UserInfoRes();userInfoRes.setUsername("阿提说说");return userInfoRes;}
}

配置客户端

目前我们客户端的配置是这样的:

spring:security:oauth2:client:registration:gitee:client-id: gitee_clientIdclient-secret: gitee_secretauthorization-grant-type: authorization_coderedirect-uri: '{baseUrl}/login/oauth2/code/{registrationId}'client-name: Giteegithub:client-id: github_clientIdclient-secret: github_secret# 自定义customize:client-id: testClientIdclient-secret: testClientSecretauthorization-grant-type: authorization_coderedirect-uri: '{baseUrl}/login/oauth2/code/{registrationId}'client-name: Customizescope:- userinfoprovider:gitee:authorization-uri: https://gitee.com/oauth/authorizetoken-uri: https://gitee.com/oauth/tokenuser-info-uri: https://gitee.com/api/v5/useruser-name-attribute: name# 自定义customize:authorization-uri: http://localhost:9000/oauth2/authorizetoken-uri: http://localhost:9000/oauth2/tokenuser-info-uri: http://localhost:9000/userinfouser-name-attribute: username

这里我们只需要修改customize部分的user-info-uriuser-name-attribute
调整后配置如下,其他部分跟原来是一样的。

          customize:authorization-uri: http://localhost:9000/oauth2/authorizetoken-uri: http://localhost:9000/oauth2/tokenuser-info-uri: http://localhost:8090/userinfouser-name-attribute: username

❗ user-name-attribute的名字,必须在user-info-uri返回的属性名中存在

整流程体验

在如上三部分配置完成后,就可以体验了,启动spring-security-resource-serverspring-security-authorization-serverspring-security-oauth2-client

浏览器访问地址:http://127.0.0.1:8080/hello,在授权完成后,即跳转回并显示结果。


ResourceServer下能看到带着token的/userinfo请求日志。

************************************************************Request received for GET '/userinfo':org.apache.catalina.connector.RequestFacade@3418bfc9servletPath:/userinfo
pathInfo:null
headers:
accept: application/json
authorization: Bearer eyJraWQiOiI5YjZjZWMzNi05ZDYyLTRkMWMtOWRiNi0wMWM1ODQzMDc1N2UiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ1c2VyIiwiYXVkIjoidGVzdENsaWVudElkIiwibmJmIjoxNjYwOTU1ODQyLCJzY29wZSI6WyJ1c2VyaW5mbyJdLCJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3Q6OTAwMCIsImV4cCI6MTY2MDk1NjE0MiwiaWF0IjoxNjYwOTU1ODQyfQ.gVWwwfzB-xNuWWUBpgGokIOy5xwV9Wkd05k3rqpk1h92b-TWENB4ZArEL--zpngSyE8iuml0vG3veCv647FDx_EY56ClM-UxH-3Wq0D2f3b6WTgFO5RpCCwRLCHahBlV5g9plr7hWYY5uX2cQ4MsC4-ltZSR6wga5LSLDB-bIK46ZmJ3DOaQFwTTCpWB4OgOuq1j59i9XkgDUc_I8WUsHB4eEDEbBJeOmdimDn5O1Ux6nDhPgLMLcpnrt3lHLmXDTk8Q7hX7YBynO2VBm6wkTeYP4a2rfinfhW-LtF1o3hm8QAY0hn1QKSEeWU5K5qiIOVeSJ5FqrYJ_VQPadT1qAQ
user-agent: Java/11
host: localhost:8090
connection: keep-aliveSecurity filter chain: [DisableEncodeUrlFilterWebAsyncManagerIntegrationFilterSecurityContextPersistenceFilterHeaderWriterFilterCsrfFilterLogoutFilterBearerTokenAuthenticationFilterRequestCacheAwareFilterSecurityContextHolderAwareRequestFilterAnonymousAuthenticationFilterSessionManagementFilterExceptionTranslationFilterFilterSecurityInterceptor
]************************************************************

总结

到此,我们通过自己搭建的授权服务器和资源服务器,完整体验了OAuth2流程,再来体会下第一篇文章中说明的交互流程。

在整个流程中,我们使用的是最严密的授权码模式,它将用户引导到授权服务器进行身份验证,授权服务器将发放的访问令牌传递给客户端,目前主流都是使用该模式,因此特别重要,要好好体会

源代码地址:https://github.com/jujunchen/21Study

Spring Security 自定义资源服务器实践相关推荐

  1. Spring Security 自定义授权服务器实践

    相关文章: OAuth2的定义和运行流程 Spring Security OAuth实现Gitee快捷登录 Spring Security OAuth实现GitHub快捷登录 Spring Secur ...

  2. spring security 自定义认证登录

    spring security 自定义认证登录 1.概要 1.1.简介 spring security是一种基于 Spring AOP 和 Servlet 过滤器的安全框架,以此来管理权限认证等. 1 ...

  3. Spring Boot集成Ueditor富文本编辑器,实现图片上传,视频上传,返回内容功能并且通过OSS转换为链接并且解决Spring Security静态资源访问以及跨域问题

    学习自https://cloud.tencent.com/developer/article/1452451 现在是晚上22点,刚刚和我们的前端交流完了富文本编辑器的一些意见和看法 还是老样子 需求 ...

  4. 3.Spring Security 自定义用户认证

    Spring Security自定义用户认证 自定义认证过程 自定义认证的过程需要实现Spring Security提供的UserDetailService接口,该接口只有一个抽象方法loadUser ...

  5. spring security自定义指南

    序 本文主要研究一下几种自定义spring security的方式 主要方式 自定义UserDetailsService 自定义passwordEncoder 自定义filter 自定义Authent ...

  6. Spring Security自定义登录验证及登录返回结果

    Spring Security自定义登录验证及登录返回结果 一.功能描述 二.处理逻辑 简单流程 自定义UserDetails 自定义UserDetailsDAO 自定义UserDetailsServ ...

  7. Spring Security——自定义认证错误提示信息及自适应返回格式解决方案

    解决方案 package com.hailiu.web.handler;import com.hailiu.model.Log; import com.hailiu.web.bean.Response ...

  8. Spring Security 自定义接口登出

    Spring Security 自定义接口登出 使用Security提供的工具,在接口内登出用户. 工具类代码 // 注入 tokenStore@Autowiredprivate final Toke ...

  9. (二)Spring Security自定义登录成功或失败处理器

    目录 一:创建登录成功处理器 二:创建登录失败处理器 三:添加处理器 三. 项目地址 我们接着上一章 Spring Security最简单的搭建,进行开发 LoginSuccessHandler 和L ...

最新文章

  1. java如何判断打印是否成功_如何验证Zebra打印机是否使用ZPL和C#成功打印(或能够检测到错误)?...
  2. python算法书籍-你也能看得懂的Python算法书
  3. r语言用行名称提取数据框信息显示na_学会这些R语言技巧至少可以节省半年时间...
  4. python 哪些比赛项目_python能做什么项目
  5. PyTorch学习笔记——语言模型
  6. SQL动态配置,动态解析SQL
  7. 【MySQL性能优化的21个最佳实践】
  8. linux进阶之子网划分
  9. git stash pop 冲突,git stash list 中的记录不会自动删除的解决方法
  10. mybatis实体类类型别名
  11. mysql回调地狱_es6 promise 所见
  12. OneR算法python实现
  13. c语言 for循环 求N分之一序列前N项和
  14. Windows使用三:笔记本打不开wifi
  15. 西电 操作系统课设 在Ubuntu18.04安装pintos
  16. 马尔科夫链预测,Python实现
  17. bcedit双系统更改启动项名称_Win7下双系统修改BCD启动项名称
  18. Dubbo的异常处理
  19. PT100(RTD)三线制测量方案
  20. 索尼sw2刷android wear,SmartWatch2 apk下载|SmartWatch2 SW2软件安卓版下载 v1.6.31 - 跑跑车安卓网...

热门文章

  1. 小老板、中老板和大老板的区别
  2. 回忆展望 | 再见2020,加油2021!
  3. 跟着Cell学作图 | 5.UMAP降维分析
  4. Allegero 异形焊盘制作
  5. 考勤打卡模块设计与实现
  6. 1272: 下载记忆  小明比较怀旧,想网上下载儿时武侠片,他用自己的血汗钱办理充值会员。会员是按月充的,每月的费用为15元。问小明充值多少元,才能将所有的武侠剧下载完。
  7. STM32第七课(TIM,HAL)
  8. 计蒜客 联想专卖店大促销 二分
  9. Objective-C开发图书推荐
  10. word里的html标签,完整word版html标签大全推荐文档