簡體   English   中英

OAuth 資源服務器如何接收訪問令牌?

[英]How OAuth resource server receives access token?

我有一個主要的 class:

@SpringBootApplication
public class Oauth2Exp {
    public static void main(String[] args) {
        SpringApplication.run(OauthDemo.class, args);
    }
}

和一個簡單的 REST 端點(檢索訪問令牌並將其與字符串“Hello world:!”一起輸出):

@RestController
@RequestMapping("/api")
public class SampleRest {
    
    @Autowired
    private OAuth2AuthorizedClientService authorizedClientService;
    
    @GetMapping("/helloworld")
    public String helloworld(Authentication authentication) {
        OAuth2AuthorizedClient authorizedClient =
                this.authorizedClientService.loadAuthorizedClient("google", authentication.getName());

        OAuth2AccessToken accessToken = authorizedClient.getAccessToken();
        
        return "Hello world!!\n" + accessToken.getTokenValue();     
    }
}

然后我有以下配置將此應用程序配置為 OAuth 客戶端:

@Configuration
public class OauthClientConfig {
    
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception
    {
        http.requestMatchers().antMatchers("/**")
            .and()
            .authorizeRequests().anyRequest().authenticated()
            .and()
            .oauth2Login();
            
        return http.build();
    }
}

和以下配置來配置與 OAuth 資源服務器相同的應用程序:

@Configuration
public class OauthResourceServerConfig {

    @Bean
    public SecurityFilterChain resourceServerfilterChain(HttpSecurity http) throws Exception
    {
        http.requestMatchers().antMatchers("/api/**")
            .and()
            .authorizeRequests().anyRequest().authenticated()
            .and()
            .oauth2ResourceServer().jwt();
        
        return http.build();
    }
}

application.yml 看起來像這樣:

spring:
  security:
    oauth2:
      client:
        registration:
          google:
            clientId: <client-id>
            clientSecret: <client-secret>
      resourceserver:
        jwt:
          issuer-uri: https://accounts.google.com

我還對 pom.xml 中的 oauth-client 和資源服務器有必要的依賴關系。 有了這一切,它工作得非常好。 REST 端點確實返回了由“Hello world:!”組成的字符串。 並訪問令牌值:

在此處輸入圖像描述

現在我猜測在哪里將授權代碼交換為訪問代碼並轉發到資源服務器 REST 端點。 OAuth 客戶端有責任交換訪問令牌的授權碼。 然而,資源服務器負責驗證傳入的訪問令牌。 當我點擊 URL localhost:8080/api/helloworld時,我直接點擊資源服務器helloworld() REST 端點。 那么它是如何接收訪問令牌的呢? OAuth 客戶端是否在 REST 端點之前被調用,例如在一些負責與訪問令牌交換授權代碼然后將其轉發到 Z50780F47F6839D47D60BC4555EE00CZ 端點的安全過濾器鏈中?

通常涉及多個組件:

  • 資源服務器(或 API / 微服務)只負責驗證訪問令牌,然后將數據提供給客戶端。

  • 客戶端最常見的是單獨的 web 或移動應用程序。 它使用授權服務器對用戶進行身份驗證,然后接收訪問令牌,然后將其發送到 API。

  • 授權服務器用於將所有 API、web 和移動應用程序的高安全性外包。

Curity Guides提供了一些示例客戶端和 API。 在您的情況下,您可以考慮將 Spring API 和 Spring 網站作為單獨的組件實現。 代碼示例將針對您選擇的任何授權服務器運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM