在學習Spring Cloud 時,遇到了受權服務oauth 相關內容時,老是隻知其一;不知其二,所以決定先把Spring Security 、Spring Security Oauth2 等權限、認證相關的內容、原理及設計學習並整理一遍。本系列文章就是在學習的過程當中增強印象和理解所撰寫的,若有侵權請告知。html
項目環境:java
- JDK1.8mysql
- Spring boot 2.xgit
- Spring Security 5.xgithub
前面幾篇文章基本上已經把Security的核心內容講得差很少了,那麼從本篇文章咱們開始接觸Spring Security Oauth2 相關的內容,這其中包括後面的 Spring Social (其本質也是基於Oauth2)。有一點要說明的是,咱們是在原有的Spring-Security 項目上繼續開發,存在一些必要的重構,但不影響前面Security的功能。redis
有關於Oauth2 的 資料,網上不少,但最值得推薦的仍是 阮一峯老師的 理解OAuth 2.0,在這裏我就不重複描述Oauth2了,但我仍是有必要提下其中的重要的點:spring
圖片中展現的流程是受權碼模式的流程,其中最核心正如圖片展現的同樣:sql
Spring 官方出品的 一個實現 Oauth2 協議的技術框架,後面的系列文章其實都是在解析它是如何實現Oauth2的。若是各位有時間的話能夠看下Spring Security Oauth2 官方文檔,個人文章分析也是依靠文檔來的。數據庫
最後,我我的總結這2者的區別:瀏覽器
在微服務開發的過程當中,通常會把受權服務器和資源服務器拆分紅2個應用程序,因此本項目採用這種設計結構,不過在開發前,咱們須要作一步重要得步驟,就是項目重構。
爲何要重構呢?由於咱們是將受權和資源2個服務器拆分了,以前開發的一些配置和功能是能夠在2個服務器共用的,因此咱們能夠講公共的配置和功能能夠單獨羅列出來,以及後面咱們開發Spring Security Oauth2 得一些公共配置(好比Token相關配置)。 咱們新建 security-core 子模塊,將以前開發的短信等功能代碼遷移到這個子模塊中。最終獲得如下項目結構:
遷移完成後,原先項目模塊更換模塊名爲 security-oauth2-authorization ,即 受權服務應用,而且 在pom.xml 中引用 security-core 依賴,遷移後該模塊的項目結構以下:
咱們能夠發現,遷移後的項目內部只有 Security相關的配置代碼和測試接口,以及靜態的html。
在 security-core 模塊的pom.xml 中引用 如下依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 不是starter,手動配置 -->
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<!--請注意下 spring-authorization-oauth2 的版本 務必高於 2.3.2.RELEASE,這是官方的一個bug:
java.lang.NoSuchMethodError: org.springframework.data.redis.connection.RedisConnection.set([B[B)V
要求必須大於2.3.5 版本,官方解釋:https://github.com/BUG9/spring-security/network/alert/pom.xml/org.springframework.security.oauth:spring-security-oauth2/open
-->
<version>2.3.5.RELEASE</version>
</dependency>複製代碼
這裏新增 spring-security-oauth2 依賴,一個針對token 的存儲策略分別引用了 redis 和 jwt 依賴。
注意這裏 spring-security-oauth2 版本必須高於 2.3.5 版本 ,否自使用 redis 存儲token 策略會報出:
org.springframework.data.redis.connection.RedisConnection.set([B[B)V 異常
security-oauth2-authorization 模塊的 pom 引用 security-core :
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- 這裏去掉 spring-security-oauth2 主要是其內部的版本是 低於2.3.5
(security-core 自己 引用的就是 2.3.5 ,但爲何這邊看到的倒是低於其版本,暫時沒找到緣由,可能統一版本管理 platform-bom 的問題吧)
,爲了防止出現異常這裏去掉,再單獨引用-->
<dependency>
<groupId>com.zhc</groupId>
<artifactId>security-core</artifactId>
<version>0.0.1-SNAPSHOT</version>
<exclusions>
<exclusion>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 不是starter,手動配置 -->
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<!--請注意下 spring-authorization-oauth2 的版本 務必高於 2.3.2.RELEASE,這是官方的一個bug:
java.lang.NoSuchMethodError: org.springframework.data.redis.connection.RedisConnection.set([B[B)V
要求必須大於2.3.5 版本,官方解釋:https://github.com/BUG9/spring-security/network/alert/pom.xml/org.springframework.security.oauth:spring-security-oauth2/open
-->
<version>2.3.5.RELEASE</version>
</dependency>複製代碼
在Spring Security Oauth2 中有一個 @EnableAuthorizationServer ,只要咱們 在項目中引用到了這個註解,那麼一個基本的受權服務就配置好了,可是實際項目中並不這樣作。好比要配置redis和jwt 2種存儲token策略共存,經過繼承 AuthorizationServerConfigurerAdapter 來實現。 下列代碼是個人一個個性化配置:
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Resource
private AuthenticationManager authenticationManager; // 一、引用 authenticationManager 支持 Password 受權模式
private final Map<String, TokenStore> tokenStoreMap; // 二、獲取到系統全部的 token存儲策略對象 TokenStore ,這裏我配置了 redisTokenStore 和 jwtTokenStore
@Autowired(required = false)
private AccessTokenConverter jwtAccessTokenConverter; // 三、 jwt token的加強器
/**
* 四、因爲存儲策略時根據配置指定的,當使用redis策略時,tokenEnhancerChain 是沒有被注入的,因此這裏設置成 required = false
*/
@Autowired(required = false)
private TokenEnhancerChain tokenEnhancerChain; // 五、token的加強器鏈
@Autowired
private PasswordEncoder passwordEncoder;
@Value("${spring.security.oauth2.storeType}")
private String storeType = "jwt"; // 六、經過獲取配置來判斷當前使用哪一種存儲策略,默認jwt
@Autowired
public AuthorizationServerConfiguration(Map<String, TokenStore> tokenStoreMap) {
this.tokenStoreMap = tokenStoreMap;
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//七、 配置一個客戶端,支持客戶端模式、密碼模式和受權碼模式
clients.inMemory() // 採用內存方式。也能夠採用 數據庫方式
.withClient("client1") // clientId
.authorizedGrantTypes("client_credentials", "password", "authorization_code", "refresh_token") // 受權模式
.scopes("read") // 權限範圍
.redirectUris("http://localhost:8091/login") // 受權碼模式返回code碼的回調地址
// 自動受權,無需人工手動點擊 approve
.autoApprove(true)
.secret(passwordEncoder.encode("123456"))
.and()
.withClient("client2")
.authorizedGrantTypes("client_credentials", "password", "authorization_code", "refresh_token")
.scopes("read")
.redirectUris("http://localhost:8092/login")
.autoApprove(true)
.secret(passwordEncoder.encode("123456"));
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
// 設置token存儲方式,這裏提供redis和jwt
endpoints
.tokenStore(tokenStoreMap.get(storeType + "TokenStore"))
.authenticationManager(authenticationManager);
if ("jwt".equalsIgnoreCase(storeType)) {
endpoints.accessTokenConverter(jwtAccessTokenConverter)
.tokenEnhancer(tokenEnhancerChain);
}
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer// 開啓/oauth/token_key驗證端口無權限訪問
.tokenKeyAccess("permitAll()")
// 開啓/oauth/check_token驗證端口認證權限訪問
.checkTokenAccess("isAuthenticated()")
//容許表單認證 請求/oauth/token的,若是配置支持allowFormAuthenticationForClients的,且url中有client_id和client_secret的會走ClientCredentialsTokenEndpointFilter
.allowFormAuthenticationForClients();
}
}複製代碼
這裏的配置分3部分:
在配置受權認證時,依賴注入了 tokenStore 、jwtAccessTokenConverter、tokenEnhancerChain,但這些對象是如何配置並注入到Spring 容器的呢?且看下面代碼:
@Configuration
public class TokenStoreConfig {
/**
* redis鏈接工廠
*/
@Resource
private RedisConnectionFactory redisConnectionFactory;
/**
* 使用redisTokenStore存儲token
*
* @return tokenStore
*/
@Bean
@ConditionalOnProperty(prefix = "spring.security.oauth2", name = "storeType", havingValue = "redis")
public TokenStore redisTokenStore() {
return new RedisTokenStore(redisConnectionFactory);
}
@Bean
PasswordEncoder passwordEncoder(){
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
/**
* jwt的配置
*
* 使用jwt時的配置,默認生效
*/
@Configuration
@ConditionalOnProperty(prefix = "spring.security.oauth2", name = "storeType", havingValue = "jwt", matchIfMissing = true)
public static class JwtTokenConfig {
@Resource
private SecurityProperties securityProperties;
/**
* 使用jwtTokenStore存儲token
* 這裏經過 matchIfMissing = true 設置默認使用 jwtTokenStore
*
* @return tokenStore
*/
@Bean
public TokenStore jwtTokenStore() {
return new JwtTokenStore(jwtAccessTokenConverter());
}
/**
* 用於生成jwt
*
* @return JwtAccessTokenConverter
*/
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter();
//生成簽名的key,這裏使用對稱加密
accessTokenConverter.setSigningKey(securityProperties.getOauth2().getJwtSigningKey());
return accessTokenConverter;
}
/**
* 用於擴展JWT
*
* @return TokenEnhancer
*/
@Bean
@ConditionalOnMissingBean(name = "jwtTokenEnhancer")
public TokenEnhancer jwtTokenEnhancer() {
return new JwtTokenEnhance();
}
/**
* 自定義token擴展鏈
*
* @return tokenEnhancerChain
*/
@Bean
public TokenEnhancerChain tokenEnhancerChain() {
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
tokenEnhancerChain.setTokenEnhancers(Arrays.asList(new JwtTokenEnhance(), jwtAccessTokenConverter()));
return tokenEnhancerChain;
}
}
}複製代碼
注意: 該配置類適用於均適用於受權和資源服務器,因此該配置類是放在 security-core 模塊
spring:
redis:
host: 127.0.0.1
port: 6379
security:
oauth2:
storeType: redis
jwt:
SigningKey: oauth2複製代碼
一、 受權碼模式:granttype=authorizationcode
(1)瀏覽器上訪問/oauth/authorize 獲取受權碼:
http://localhost:9090/oauth/authorize?response_type=code&client_id=client1&scope=read&state=test&redirect_uri=http://localhost:8091/login複製代碼
若是是沒有登錄過,則跳轉到登錄界面(這裏帳戶密碼登錄和短信驗證碼登錄都可),成功跳轉到 咱們設置的回調地址(咱們這個是單點登錄客戶端),咱們能夠從瀏覽器地址欄看到 code碼
(2)Postman請求/oauth/token 獲取token:
localhost:9090/oauth/token?grant_type=authorization_code&code=i4ge7B&redirect_uri=http://localhost:8091/login複製代碼
注意在 Authorization 填寫 client信息,下面是 curl 請求:
curl -X POST \
'http://localhost:9090/oauth/token?grant_type=authorization_code&code=Q38nnC&redirect_uri=http://localhost:8091/login' \
-H 'Accept: */*' \
-H 'Accept-Encoding: gzip, deflate' \
-H 'Authorization: Basic Y2xpZW50MToxMjM0NTY=' \
-H 'Cache-Control: no-cache' \
-H 'Connection: keep-alive' \
-H 'Content-Length: ' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-H 'Cookie: remember-me=; JSESSIONID=F6F6DE2968113DDE4613091E998D77F4' \
-H 'Host: localhost:9090' \
-H 'Postman-Token: f37b9921-4efe-44ad-9884-f14e9bd74bce,3c80ffe3-9e1c-4222-a2e1-9694bff3510a' \
-H 'User-Agent: PostmanRuntime/7.16.3' \
-H 'cache-control: no-cache'複製代碼
響應報文:
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiI5MDAxIiwic2NvcGUiOlsicmVhZCJdLCJleHAiOjE1Njg2NDY0NzksImF1dGhvcml0aWVzIjpbImFkbWluIl0sImp0aSI6ImY5ZDBhNmZhLTAxOWYtNGU5Ny1iMmI4LWI1OTNlNjBiZjk0NiIsImNsaWVudF9pZCI6ImNsaWVudDEiLCJ1c2VybmFtZSI6IjkwMDEifQ.4BjG_LggZt2RJr0VzXTSmsk71EIUDGvrQsL_OPsg8VA",
"token_type": "bearer",
"refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiI5MDAxIiwic2NvcGUiOlsicmVhZCJdLCJhdGkiOiJmOWQwYTZmYS0wMTlmLTRlOTctYjJiOC1iNTkzZTYwYmY5NDYiLCJleHAiOjE1NzExOTUyNzksImF1dGhvcml0aWVzIjpbImFkbWluIl0sImp0aSI6IjU1NTRmYjdkLTBhZGItNGI4MS1iOGNlLWIwOTk2NjM1OTI4MCIsImNsaWVudF9pZCI6ImNsaWVudDEiLCJ1c2VybmFtZSI6IjkwMDEifQ.TA1frc46XRkNgl3Y_n72rM0nZ5QceWH3zJFmR7CkHQ4",
"expires_in": 43199,
"scope": "read",
"username": "9001",
"jti": "f9d0a6fa-019f-4e97-b2b8-b593e60bf946"
}複製代碼
二、 密碼模式: grant_type=password
Postman:
http://localhost:9090/oauth/token?username=user&password=123456&grant_type=password&scope=read&client_id=client1&client_secret=123456複製代碼
curl:
curl -X POST \
'http://localhost:9090/oauth/token?username=user&password=123456&grant_type=password&scope=read&client_id=client1&client_secret=123456' \
-H 'Accept: */*' \
-H 'Accept-Encoding: gzip, deflate' \
-H 'Cache-Control: no-cache' \
-H 'Connection: keep-alive' \
-H 'Content-Length: ' \
-H 'Cookie: remember-me=; JSESSIONID=F6F6DE2968113DDE4613091E998D77F4' \
-H 'Host: localhost:9090' \
-H 'Postman-Token: f41c7e67-1127-4b65-87ed-21b3e00cfae3,08168e2e-1818-42f8-b4c4-cafd4aa0edc4' \
-H 'User-Agent: PostmanRuntime/7.16.3' \
-H 'cache-control: no-cache'
複製代碼
三、 客戶端模式 : granttype=clientcredentials
Postman:
localhost:9090/oauth/token?scope=read&grant_type=client_credentials複製代碼
注意在 Authorization 填寫 client信息,下面是 curl 請求:
curl:
curl -X POST \
'http://localhost:9090/oauth/token?scope=read&grant_type=client_credentials' \
-H 'Accept: */*' \
-H 'Accept-Encoding: gzip, deflate' \
-H 'Authorization: Basic Y2xpZW50MToxMjM0NTY=' \
-H 'Cache-Control: no-cache' \
-H 'Connection: keep-alive' \
-H 'Content-Length: 35' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-H 'Cookie: remember-me=; JSESSIONID=F6F6DE2968113DDE4613091E998D77F4' \
-H 'Host: localhost:9090' \
-H 'Postman-Token: a8d3b4a2-7aee-4f0d-8959-caa99a412012,f5e41385-b2b3-48d2-aa65-8b1d1c075cab' \
-H 'User-Agent: PostmanRuntime/7.16.3' \
-H 'cache-control: no-cache' \
-d 'username=zhoutaoo&password=password'
複製代碼
受權服務開發,咱們繼續延用以前的security配置,包括 UserDetailsService及其登錄配置,在其基礎上咱們新增了受權配置,完成整個受權服務的搭建及測試。
因爲資源服務器是個權限的應用程序,咱們新建 security-oauth2-authentication 子模塊做爲資源服務器應用。
security-oauth2-authentication 模塊 pom 引用 security-core:
<dependency>
<groupId>com.zhc</groupId>
<artifactId>security-core</artifactId>
<version>0.0.1-SNAPSHOT</version>
<exclusions>
<exclusion>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 不是starter,手動配置 -->
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<!--請注意下 spring-authorization-oauth2 的版本 務必高於 2.3.2.RELEASE,這是官方的一個bug:
java.lang.NoSuchMethodError: org.springframework.data.redis.connection.RedisConnection.set([B[B)V
要求必須大於2.3.5 版本,官方解釋:https://github.com/BUG9/spring-security/network/alert/pom.xml/org.springframework.security.oauth:spring-security-oauth2/open
-->
<version>2.3.5.RELEASE</version>
</dependency>複製代碼
整個資源服務的配置主要分3個點:
@Configuration
@EnableResourceServer // 1
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
private final Map<String,TokenStore> tokenStoreMap;
@Value("${spring.security.oauth2.storeType}")
private String storeType = "jwt";
@Autowired
public ResourceServerConfiguration(Map<String, TokenStore> tokenStoreMap) {
this.tokenStoreMap = tokenStoreMap;
}
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.tokenStore(tokenStoreMap.get(storeType + "TokenStore")); // 2
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
.requestMatchers().anyRequest()
.and()
.anonymous()
.and()
.authorizeRequests()
//配置oauth2訪問(測試接口)控制,必須認證事後才能夠訪問
.antMatchers("/oauth2/**").authenticated(); // 3
}
}複製代碼
因爲受權服務器採用不一樣tokenStore,因此這裏也要引用 其 配置:
spring:
redis:
host: 127.0.0.1
port: 6379
security:
oauth2:
storeType: jwt
jwt:
SigningKey: oauth2複製代碼
@RestController
@RequestMapping("/oauth2")
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Slf4j
public class TestEndpoints {
@GetMapping("/getUser")
@PreAuthorize("hasAnyAuthority('user')")
public String getUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return "User: " + authentication.getPrincipal().toString();
}
}
複製代碼
咱們將從受權服務器獲取到的token進行訪問測試接口:
Postman:
http://localhost:8090/oauth2/getUser?access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJyZWFkIl0sImV4cCI6MTU2ODY0ODEyMCwianRpIjoiNDQ0NWQ1ZDktYWZlMC00N2Y1LTk0NGItZTEyNzI1NzI1M2M1IiwiY2xpZW50X2lkIjoiY2xpZW50MSIsInVzZXJuYW1lIjoiY2xpZW50MSJ9.pOnIcmjy2ex7jlXvAGslEN89EyFPYPbW-l4f_cyK17k複製代碼
curl:
curl -X GET \
'http://localhost:8090/oauth2/getUser?access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJyZWFkIl0sImV4cCI6MTU2ODY0ODEyMCwianRpIjoiNDQ0NWQ1ZDktYWZlMC00N2Y1LTk0NGItZTEyNzI1NzI1M2M1IiwiY2xpZW50X2lkIjoiY2xpZW50MSIsInVzZXJuYW1lIjoiY2xpZW50MSJ9.pOnIcmjy2ex7jlXvAGslEN89EyFPYPbW-l4f_cyK17k' \
-H 'Accept: */*' \
-H 'Accept-Encoding: gzip, deflate' \
-H 'Cache-Control: no-cache' \
-H 'Connection: keep-alive' \
-H 'Cookie: remember-me=; JSESSIONID=F6F6DE2968113DDE4613091E998D77F4' \
-H 'Host: localhost:8090' \
-H 'Postman-Token: 07ec53c7-9051-439b-9603-ef0fe93664fa,e4a5b46e-feb7-4bf8-ab53-0c33aa44f661' \
-H 'User-Agent: PostmanRuntime/7.16.3' \
-H 'cache-control: no-cache'
複製代碼
Spring security Oauth2 就是一套標準的Oauth2實現,咱們能夠經過開發進一步的瞭解Oauth2的,但總體上涉及到的技術仍是不少的,好比redis、jwt等等。本文僅僅只是簡單的演示Spring security Oauth2 Demo,但願對你有幫助,若是你還對想深刻解析下Spring Security Oauth2,那麼請繼續關注我,後續會解析其原理。
本文介紹Spring security Oauth2開發的代碼能夠訪問代碼倉庫 ,項目的github 地址 : https://github.com/BUG9/spring-security
若是您對這些感興趣,歡迎star、follow、收藏、轉發給予支持!