> 本博文翻譯自[官方文檔](https://projects.spring.io/spring-security-oauth/docs/oauth2.html)。
Spring Security 官方已經棄用OAuth2項目了,你知道嗎?Spring Security5.2.x版本以上提供了最新的方式。
## 一、關于授權服務器
### AuthorizationServerConfigurer的配置
使用注解`@EnableAuthorizationServer`啟用授權服務器。授權服務器可以對ClientDetailsService、AuthorizationServerSecurity、AuthorizationServerEndpoints進行配置。
分別對應三個配置類:
- ClientDetailsServiceConfigurer: a configurer that defines the client details service. Client details can be initialized, or you can just refer to an existing store.
- `AuthorizationServerSecurityConfigurer`: tolen獲取的安全性設置。
- `AuthorizationServerEndpointsConfigurer`: 定義了授權、token獲取的相關服務。
### 配置Client Details
`ClientDetailsServiceConfigurer`會被`AuthorizationServerConfigurer`回調。Client Details Service可以被設置為基于內存或者是JDBC的實現,關鍵屬性包括:
- clientId: (非空)Client編號.
- secret: client secret.
- scope: 客戶端訪問范圍限制。如果scope設置為空,則不進行限制。
- authorizedGrantTypes: Grant types that are authorized for the client to use. Default value is empty.
- authorities: Authorities that are granted to the client (regular Spring Security authorities).
### 管理token
`AuthorizationServerTokenServices`用來管理token存儲的實現,默認存儲是在內存中的。
- InMemoryTokenStore:適合單節點開發環境;
- JdbcTokenStore :各個服務之間可以共享token存儲;
- JWTTokenStore:
### 配置EndPoint URLS
> 什么是EndPoint URLS?作為小白的我,經常感到水土不服。
框架自帶的路徑:
- `/oauth/authorize`:認證地址;
- `/oauth/token`:token地址;
- `/oauth/confirm_access`:用戶授權的時候打開的地址;
- `/oauth/error`:授權錯誤時打開的地址;
- `/oauth/check_token`:資源服務器解密驗證token;
- `/oauth/token_key`:使用JWT token時暴露公有key進行token驗證;
## 二、資源(Resource)服務器配置
資源服務器是基于token保護資源服務的。Spring Oauth協議提供Security認證Filter(`OAuth2AuthenticationProcessingFilter`的實現)來實現這個功能。
開啟方法:在配置類中添加注解:`@EnableResourceServer`。可用配置有:
- tokenServices: 定義token services的一個bean (ResourceServerTokenServices的實例).
- resourceId: 資源id (可選,但建議使用,如果存在auth服務,將由auth服務器驗證).
- other extension points for the resourecs server (e.g. tokenExtractor for extracting the tokens from incoming requests)
- request matchers for protected resources (defaults to all)
- access rules for protected resources (defaults to plain "authenticated")
- other customizations for the protected resources permitted by the HttpSecurity configurer in Spring Security
## 三、OAuth2.0 Client
> 基本概念:
- `OAuth2ProtectedResourceDetails`:被保護的資源bean;
### 被保護資源配置
- `id`: 資源的ID。客戶端可以用來查找資源;這個ID在OAuth protocol中是無用的,它也用作bean的ID。
- `clientId`: OAuth client的id. This is the id by which the OAuth provider identifies your client.
- `clientSecret`: The secret associated with the resource. By default, no secret is empty.
- `accessTokenUri`: The URI of the provider OAuth endpoint that provides the access token.
- `scope`: 多個scope之間使用','連接的字符串配置,可以訪問資源資源。默認不指定任何的scope。
- `clientAuthenticationScheme`: The scheme used by your client to authenticate to the access token endpoint. Suggested values: "http_basic" and "form". Default: "http_basic". See section 2.1 of the OAuth 2 spec.
> Different grant types have different concrete implementations of OAuth2ProtectedResourceDetails (e.g. ClientCredentialsResource for "client_credentials" grant type). For grant types that require user authorization there is a further property:
- `userAuthorizationUri`: The uri to which the user will be redirected if the user is ever needed to authorize access to the resource. Note that this is not always required, depending on which OAuth 2 profiles are supported.
### 客戶端的配置
使用注解:`@EnableOAuth2Client`,注解的背后做了兩件事情:
- 創建了一個ID為`oauth2ClientContextFilter`的filter,用來存儲當前請求和上下文。在認證請求過程中用于管理OAuth認證url的重定向。
- 請求過程中,創建了一個類型為`AccessTokenRequest`的bean,授權碼可以用這個bean來防止客戶端與單個用戶的狀態沖突。
`AccessTokenRequest`在OAuth2RestTemplate是這樣的使用的:
```java
@Autowired
private OAuth2ClientContext oauth2Context;
@Bean
public OAuth2RestTemplate sparklrRestTemplate() {
return new OAuth2RestTemplate(sparklr(), oauth2Context);
}
```
### 資源訪問
在Spring3中RestTemplate是訪問資源時推薦的方式,Spring Security對其進行了拓展,只需要實例化`OAuth2ProtectedResourceDetails`就好了。
### 客戶端token的保持
客戶端不需要持久化token,但是客戶端重啟時用戶不需要獲取一個新的token。 `ClientTokenServices` 接口定義了必要的功能用來持久化 OAuth 2.0 tokens以區分用戶。系統提供了一種JDBC的實現。想要使用這個特性,需要向OAUthRestTemplate提供額外的`TokenProvider`配置。
```java
@Bean
@Scope(value = "session", proxyMode = ScopedProxyMode.INTERFACES)
public OAuth2RestOperations restTemplate() {
OAuth2RestTemplate template = new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(accessTokenRequest));
AccessTokenProviderChain provider = new AccessTokenProviderChain(Arrays.asList(new AuthorizationCodeAccessTokenProvider()));
provider.setClientTokenServices(clientTokenServices());
return template;
}
```
## 感慨一下
> 之前在網絡上搜了不少關于Spring Security Oauth2相關的資料,理解一直不甚透徹。今日官網文檔一看,發現Spring Security Oauth2已經是Spring4.x時代的產物了。說明自己學習新知識的習慣還是不太成熟。另外說一點,看英文文檔的表述比谷歌的自動翻譯要好太多了。
- 簡介
- 更新說明
- 其他作品
- 第一部分 Java框架基礎
- 第一章 Java基礎
- 多線程實戰
- 嘗試一下Guava帶返回值的多線程處理類ListenableFuture
- LocalDate和Date有什么區別
- JAVA8接口增強實踐
- 第二章 Spring框架基礎
- MVC究竟是個啥?
- @ApiImplicitParam
- 七種方式,教你在SpringBoot初始化時搞點事情!
- Spring事務狀態
- maven
- Mybatis小總結
- mybatis-plus的使用
- 第三章 SpringSecurity實戰
- 基于SpringSecurity+jwt的用戶認證
- spring-security-oauth2
- 第四章 數據庫
- mysql
- mysql授權
- mysql數據庫三個關鍵性能指標--TPS\QPS\IOPS
- 梳理一下那些年Mysql的弱語法可能會踩的坑
- 關于Mysql的“字符串”數值的轉換和使用
- 憑這一文咱把事務講透
- Mysql性能優化
- 查詢性能優化
- 不常用的一些語法
- elasticsearch
- elasticsearch文檔操作
- 索引的基本操作
- java操作ElaticSearch
- elasticsearch中的各種查詢
- DB與ES混合應用可能存在的問題及解決方案探索
- 使用es必須要知道的一些知識點:索引篇
- Es中的日期操作
- MongoDB
- 入門篇(了解非關系型數據庫 NoSQL - MongoDB)
- 集群分片 (高級篇)
- 互聯網大廠的建表規范
- 第五章 中間件
- nginx
- nginx動靜分離配置,這個雷你踩過嗎?
- Canal
- Sharding-jdbc
- 水平分庫實踐
- kafka
- 第六章 版本管理
- git
- Not currently on any branch 情況提交版本
- 第七章 IO編程
- 第八章 JVM實戰調優
- jvisualvm
- jstat
- 第二部分 高級項目實戰篇
- 第一章 微信開發實戰
- 第二章 文件處理
- 使用EasyExcel處理導入導出
- 第三章 踩坑指南
- 郵件發送功能
- 第三部分 架構實戰篇
- 第一章 架構實戰原則
- 接口防止重復調用的一種方案
- 第二章 高并發緩存一致性管理辦法
- 第三章 異地多活場景下的數據同步之道
- 第四章 用戶體系
- 集成登錄
- auth-sso的管理
- 第五章 分庫分表場景
- 第六章 秒殺與高并發
- 秒殺場景
- 第七章 業務中臺
- 中臺的使用效果是怎樣的?
- 通用黑白名單方案
- 第八章 領域驅動設計
- 第十一章 微服務實戰
- Nacos多環境管理之道
- logback日志雙寫問題及Springboot項目正確的啟動方式
- 第四部分 優雅的代碼
- java中的鏈式編程
- 面向對象
- 開發原則
- Stream操作案例分享
- 注重性能的代碼
- 第五部分 談談成長
- 新手入門指北
- 不可不知的調試技巧
- 構建自己的知識體系
- 我是如何做筆記的
- 有效的提問
- 謹防思維定勢
- 學會與上級溝通
- 想清楚再去做
- 碎片化學習
- 第六部分 思維導圖(付費)
- 技術基礎篇
- 技術框架篇
- 數據存儲篇
- 項目實戰篇
- 第七部分 吾愛開源
- 7-1 麻雀聊天
- 項目啟動
- 前端登錄無請求問題解決
- websocket測試
- 7-2 ocp微服務框架
- evm框架集成
- 項目構建與集成
- zentao-center
- 二次開發:初始框架的搭建
- 二次開發:增加細分菜單、權限到應用
- 7-3 書棧網
- 項目啟動
- 源碼分析
- 我的書架
- 文章發布機制
- IM
- 第八章 團隊管理篇
- 大廠是怎么運作的
- 第九章 碼山有道
- 簡歷內推
- 聯系我內推
- 第十章 學點前端
- Vue