Spring Security OAuth2 Demo —— 客戶端模式(ClientCredentials)


前情回顧

前幾節分享了OAuth2的流程與其它三種授權模式,這幾種授權模式復雜程度由大至小:授權碼模式 > 隱式授權模式 > 密碼模式 > 客戶端模式

本文要講的是最后一種也是最簡單的模式:客戶端模式

其中客戶端模式的流程是:客戶端使用授權服器給的標識與secret訪問資源服務器獲取token

本文目標

編寫與說明密碼模式的Spring Security Oauth2的demo實現,讓未了解過相關知識的讀者對客戶端模式授權流程有個更直觀的概念

以下分成授權服務器與資源服務器分別進行解釋,只講關鍵部分,詳情見Github:https://github.com/hellxz/spring-security-oauth2-learn

適用場景

沒有用戶與授權服務器交互,完全以機器形式獲取授權與使用授權,客戶端機器 <-> 授權服務器,這種方式主要用於第一方應用中

搭建密碼模式授權服務器

代碼結構與之前兩個模式相同,這里便不再進行說明

SecurityConfig配置

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated();
    }
}

基本的SpringSecurity的配置,開啟Spring Security的Web安全功能,填了一個用戶信息,所有資源必須經過授權才可以訪問

AuthorizationConfig授權服務器配置

@Configuration
@EnableAuthorizationServer
public class AuthorizationConfig extends AuthorizationServerConfigurerAdapter {
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        //@formatter:off
        clients.inMemory()
                .withClient("user-center")
                .secret(passwordEncoder().encode("12345"))
                .authorizedGrantTypes("client_credentials") //主要配置這里為client_credentials
                .scopes("all");
        //@formatter:on
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.allowFormAuthenticationForClients()
                .checkTokenAccess("isAuthenticated()");
    }
}

這里開啟了授權服務器的功能,相對其它模式主要是authorizedGrantTypes這里設置的client_credentials,其余不變

application.properties配置sever.port=8080

搭建資源服務器

這里的關鍵就是ResourceConfig,配置比較簡單與其它幾個模式完全一致,模式的不同主要表現在授權服務器與客戶端服務器上,資源服務器只做token的校驗與給予資源

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Bean
    public RemoteTokenServices remoteTokenServices(){
        final RemoteTokenServices remoteTokenServices = new RemoteTokenServices();
        remoteTokenServices.setCheckTokenEndpointUrl("http://localhost:8080/oauth/check_token");
        remoteTokenServices.setClientId("user-center");
        remoteTokenServices.setClientSecret("12345");
        return remoteTokenServices;
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.stateless(true);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
        http.authorizeRequests().anyRequest().authenticated();
    }
}

ResourceController主要接收一個用戶名,返回一個username與email的json串

application.properties設置server.port=8081

准備工作到這里就差不多了,開始測試

測試流程

這里客戶端使用postman手動發送請求進行演示

  • POST訪問/oauth/token端點,獲取token

    這里除了請求頭使用client標識信息外,添加一個grant_type=client_credentials,只需要這兩個參數就可以得到token

  • token返回值

    {
        "access_token": "3efcb9db-2c15-42db-b3f0-3c535439c799",
        "token_type": "bearer",
        "expires_in": 43199,
        "scope": "all"
    }
    
  • 使用token調用資源,訪問http://localhost:8081/user/hellxz001,注意使用token添加Bearer請求頭

尾聲

本文是OAuth2授權模式代碼部分的最后一個,后續分別記錄下JWT與Redis兩種tokenStore方式


免責聲明!

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



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