Spring Security OAuth2.0認證授權二:搭建資源服務
阿新 • • 發佈:2021-01-11
在上一篇文章[Spring Security OAuth2.0認證授權一:框架搭建和認證測試](https://www.cnblogs.com/kuangdaoyizhimei/p/14250374.html) 詳細講解了如何搭建一個基於spring boot + oauth2.0的認證服務,這篇文章將會介紹如何搭建一個資源服務。
根據oath2.0協議內容,應當有一個資源服務管理資源並提供訪問安全控制。
## 1. 引入maven依賴
``` xml
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter-security
org.springframework.cloud
spring-cloud-starter-oauth2
org.springframework.security
spring-security-jwt
com.alibaba
fastjson
org.projectlombok
lombok
```
這裡雖然引入了jwt的依賴,但是暫時還未用到。
## 2. 配置配置檔案
``` yaml
server:
port: 30001
spring:
application:
name: resource-server
```
## 3. 新建啟動類
``` java
@SpringBootApplication
public class ResourceServerApplication {
public static void main(String[] args) {
SpringApplication.run(ResourceServerApplication.class, args);
}
}
```
## 4. Resource服務核心配置
### 4.1 新建ResouceServerConfig類
該類需要繼承ResourceServerConfigurerAdapter類並需要使用@EnableResourceServer註解註釋。
```java
@Configuration
@EnableResourceServer
public class ResouceServerConfig extends ResourceServerConfigurerAdapter {
......
}
```
### 4.2 核心配置
重寫ResouceServerConfig類以下方法以實現ResourceServer的基本配置:
org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter#configure(org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer)
``` java
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources
.resourceId(RESOURCE_ID)
.tokenServices(resourceServerTokenServices)//令牌服務
.stateless(true);
}
```
- resourceId方法標誌了該服務的id,需要和在auth-center服務中配置的id一致。
- tokenServices方法指定了令牌管理的例項,Bean建立方法如下
``` java
@Bean
public ResourceServerTokenServices resourceServerTokenServices(){
RemoteTokenServices remoteTokenServices = new RemoteTokenServices();
remoteTokenServices.setCheckTokenEndpointUrl("http://127.0.0.1:30000/oauth/check_token");
remoteTokenServices.setClientId("c1");
remoteTokenServices.setClientSecret("secret");
return remoteTokenServices;
}
```
- stateless方法指定了當前資源是否僅僅允許token驗證的方法進行校驗,預設為true
### 4.3 auth2.0安全配置
``` java
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/**").access("#oauth2.hasScope('all')")
.and()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
}
```
該配置和下面的Web安全配置很像,但是不一樣,這裡僅僅對auth2.0的安全進行配置。這裡的`.antMatchers("/**").access("#oauth2.hasScope('all')")`表示所有的請求攜帶的令牌都必須擁有all的授權範圍,其中all授權範圍必須和認證服務中的配置相一致。
### 4.4 Web安全配置
``` java
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf()
.disable()
.authorizeRequests()
.antMatchers("/r/r1").hasAuthority("p2")
.antMatchers("/r/r2").hasAuthority("p2")
.antMatchers("/**").authenticated()//所有的r/**請求必須認證通過
.anyRequest().permitAll();//其它所有請求都可以隨意訪問
}
}
```
### 4.5 暴露資源介面
``` java
@RestController
@Slf4j
public class OrderController {
@GetMapping("/r1")
@PreAuthorize("hasAnyAuthority('p1')")
public String r1(){
return "訪問資源r1";
}
}
```
由於4.4啟用了prePostEnabled,所以這裡可以使用@PreAuthorize註解對資源安全請求進行管理。
`@PreAuthorize("hasAnyAuthority('p1')")`表示請求者必須擁有p1許可權,p1許可權定義在auth-center服務表的t_permission表。
## 5. 介面測試
原始碼地址:https://gitee.com/kdyzm/spring-security-oauth-study/tree/v3.0.0
### 5.1 準備工作
首先,閱讀下 https://gitee.com/kdyzm/spring-security-oauth-study/tree/v3.0.0/auth-center 專案的自述檔案,配置好資料庫和表、配置檔案,配置完成之後分別啟動認證服務auth-center服務(埠號30000)和資源服務resource-server(埠號30001)。
### 5.2 獲取token
閱讀下 https://gitee.com/kdyzm/spring-security-oauth-study/tree/v3.0.0/auth-center 專案的自述檔案,有四種獲取token的方式。
### 5.3 請求資源服務
假設在5.2已經成功獲取到了token:
``` json
{
"access_token": "11c5eaec-768f-400a-85e1-e2b52276b83d",
"token_type": "bearer",
"refresh_token": "34eb5d57-de7e-4f26-b35e-64162c64117e",
"expires_in": 7199,
"scope": "all"
}
```
接下來要攜帶著token請求資源服務:
| header | value |
| :-----------: | :-----------------------------------------: |
| Authorization | Bearer 0cc2da26-b634-4ccb-a8fe-14f454a13090 |
GET請求:http://127.0.0.1:30001/r1
請求成功,結果返回:
``` json
訪問資源r1
```
請求失敗,結果返回:
``` json
{
"error": "invalid_token",
"error_description": "0cc2da26-b634-4ccb-a8fe-14f454a13090"
}
```
### 5.4 請求演示
下面演示使用postman基於密碼模式獲取token並請求資源服務的過程:
![](https://img2020.cnblogs.com/blog/516671/202101/516671-20210110221525922-832551950.gif)
## 6.原始碼
原始碼地址:https://gitee.com/kdyzm/spring-security-oauth-study/tree/v3.0.0
我的部落格地址:https://blog.kd