Spring Cloud Security OAuth2 實現資源服務配置以及測試

@EnableResourceServer 註解到一個 @Configuration 配置類上,並且必須使用 ResourceServerConfigurer 這個 配置對象來進行配置(可以選擇繼承自 ResourceServerConfigurerAdapter 然後覆寫其中的方法,參數就是這個 對象的實例),下面是一些可以配置的屬性:

ResourceServerSecurityConfigurer中主要包括:

(1)tokenServices:ResourceServerTokenServices 類的實例,用來實現令牌服務。

(2)tokenStore:TokenStore類的實例,指定令牌如何訪問,與tokenServices配置可選

(3)resourceId:這個資源服務的ID,這個屬性是可選的,但是推薦設置並在授權服務中進行驗證。 其他的拓展屬性例如 tokenExtractor 令牌提取器用來提取請求中的令牌。

HttpSecurity配置這個與Spring Security類似:

(1)請求匹配器,用來設置需要進行保護的資源路徑,默認的情況下是保護資源服務的全部路徑。

(2)通過http.authorizeRequests()來設置受保護資源的訪問規則

(3)其他的自定義權限保護規則通過 HttpSecurity 來進行配置

@EnableResourceServer 註解自動增加了一個類型爲 OAuth2AuthenticationProcessingFilter 的過濾器鏈
編寫ResouceServerConfifig
package com.oauth.security.config;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

/**
 * @ClassName ResouceServerConfig
 * @Description
 * @Author
 * @Date 2020/5/10 14:17
 * @Version 1.0
 **/
public class ResouceServerConfig extends ResourceServerConfigurerAdapter {
    public static final String RESOURCE_ID = "res1";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(RESOURCE_ID).tokenServices(tokenService()).stateless(true);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/**").access("#oauth2.hasScope('all')")
                .and().csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}

ResourceServerTokenServices 是組成授權服務的另一半,如果你的授權服務和資源服務在同一個應用程序上的 話,你可以使用 DefaultTokenServices ,這樣的話,你就不用考慮關於實現所有必要的接口的一致性問題。如果 你的資源服務器是分離開的,那麼你就必須要確保能夠有匹配授權服務提供的 ResourceServerTokenServices,它 知道如何對令牌進行解碼。

令牌解析方法: 使用 DefaultTokenServices 在資源服務器本地配置令牌存儲、解碼、解析方式 使用 RemoteTokenServices 資源服務器通過 HTTP 請求來解碼令牌,每次都請求授權服務器端點 /oauth/check_token 使用授權服務的 /oauth/check_token 端點你需要在授權服務將這個端點暴露出去,以便資源服務可以進行訪問, 這在咱們授權服務配置中已經提到了,下面是一個例子,在這個例子中,我們在授權服務中配置了 /oauth/check_token 和 /oauth/token_key 這兩個端點:

//資源服務令牌解析服務
    @Bean
    public ResourceServerTokenServices tokenService() {
        //使用遠程服務請求授權服務器校驗token,必須指定校驗token 的url、client_id,client_secret
        RemoteTokenServices service = new RemoteTokenServices();
        service.setCheckTokenEndpointUrl("http://localhost:53020/uaa/oauth/check_token");
        service.setClientId("c1");
        service.setClientSecret("secret");
        return service;
    }

編寫controller:

package com.oauth.security.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName OrderController
 * @Description
 * @Author 
 * @Date 2020/5/10 14:49
 * @Version 1.0
 **/
@RestController
public class OrderController {
    @GetMapping(value = "/r1")
    @PreAuthorize("hasAnyAuthority('p1')")
    public String r1() {
        return "訪問資源1";
    }
}

配置security conifg

package com.oauth.security.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @ClassName WebSecurityConfig
 * @Description
 * @Author
 * @Date 2020/5/10 15:16
 * @Version 1.0
 **/
@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("/r/**").authenticated()//所有/r/**的請求必須認證通
        .anyRequest().permitAll()//除了/r/**,其它的請求可以訪問 ;
    }
}

然後我們來測試一下:

(1)啓動兩個服務

(2)申請令牌

(3)訪問資源(token的參數名稱爲:Authorization,值爲:Bearer token

這裏是在header裏面的

源碼:[email protected]:Zesystem/oauth2.0_init.git

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章