Spring Security OAuth2.0認證授權二:搭建資源服務


在上一篇文章Spring Security OAuth2.0認證授權一:框架搭建和認證測試 詳細講解了如何搭建一個基於spring boot + oauth2.0的認證服務,這篇文章將會介紹如何搭建一個資源服務。

根據oath2.0協議內容,應當有一個資源服務管理資源並提供訪問安全控制。

1. 引入maven依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-jwt</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

這里雖然引入了jwt的依賴,但是暫時還未用到。

2. 配置配置文件

server:
  port: 30001
spring:
  application:
    name: resource-server

3. 新建啟動類

@SpringBootApplication
public class ResourceServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ResourceServerApplication.class, args);
    }
}

4. Resource服務核心配置

4.1 新建ResouceServerConfig類

該類需要繼承ResourceServerConfigurerAdapter類並需要使用@EnableResourceServer注解注釋。

@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)

@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
    resources
        .resourceId(RESOURCE_ID)
        .tokenServices(resourceServerTokenServices)//令牌服務
        .stateless(true);
}
  • resourceId方法標志了該服務的id,需要和在auth-center服務中配置的id一致。
  • tokenServices方法指定了令牌管理的實例,Bean創建方法如下
    @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安全配置

@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安全配置

@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 暴露資源接口

@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:

{
    "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

請求成功,結果返回:

訪問資源r1

請求失敗,結果返回:

{
    "error": "invalid_token",
    "error_description": "0cc2da26-b634-4ccb-a8fe-14f454a13090"
}

5.4 請求演示

下面演示使用postman基於密碼模式獲取token並請求資源服務的過程:

6.源代碼

源代碼地址:https://gitee.com/kdyzm/spring-security-oauth-study/tree/v3.0.0

我的博客地址:https://blog.kdyzm.cn/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM