【问题标题】:Spring Resource Server with OAuth2 to relay access token使用 OAuth2 中继访问令牌的 Spring 资源服务器
【发布时间】:2020-12-29 03:44:28
【问题描述】:

我有一个受 OAuth2 (KeyCloak) 保护的 Spring Boot 资源服务器。我可以使用 Bearer Token 访问端点。现在,我想调用另一个受 Auth Server 保护的服务。我想转发令牌。我找不到关于如何操作的明确指南。

我的依赖是:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>

我的 application.yml 是这样的:

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: <info>

我正在尝试创建 OAuth2RestTemplate,例如:

    @Bean
    public OAuth2RestTemplate oauth2RestTemplate(OAuth2ClientContext oauth2ClientContext, OAuth2ProtectedResourceDetails details) {
        return new OAuth2RestTemplate(details, oauth2ClientContext);
    }   

但我收到错误:

required a bean of type 'org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails' that could not be found.

我该如何解决这个问题?

【问题讨论】:

    标签: java spring-oauth2 oauth2resttemplate


    【解决方案1】:

    经过大量研究和反复试验,我想出的解决方案是:

    添加依赖

            <dependency>
                <groupId>org.springframework.security.oauth.boot</groupId>
                <artifactId>spring-security-oauth2-autoconfigure</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-jwt</artifactId>
                <version>1.1.1.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
            </dependency>
    

    @EnableOAuth2Client
    

    在 application.yml 中,我添加了

    security:
      oauth2:
        keycloak:
          clientId: <CLIENT_ID>
          clientSecret: <CLIENT_SECRET>
          grantType: client_credentials
          accessTokenUri: <URI>
          userAuthorizationUri: <URI>
          scope: openid profile email
    

    配置

    
        @Bean
        @ConfigurationProperties("security.oauth2.keycloak")
        protected OAuth2ProtectedResourceDetails keycloakOAuth2Details() {
            return new ClientCredentialsResourceDetails();
        }
    
        
        @LoadBalanced
        @Bean
        public OAuth2RestTemplate restTemplate(RestTemplateCustomizer customizer) {
            OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(keycloakOAuth2Details);
            customizer.customize(restTemplate);
            return restTemplate;
        }
    

    我不确定依赖是否都是必要的。

    【讨论】:

    • 嘿 Ranpa,为什么我们需要将这些值添加到 app.properties...我们不应该只使用资源服务器。我认为这意味着我不应该添加任何客户 ID 等......
    猜你喜欢
    • 2019-05-27
    • 1970-01-01
    • 2023-02-22
    • 2021-12-26
    • 2018-12-26
    • 2016-02-03
    • 2018-05-12
    • 1970-01-01
    • 2020-04-16
    相关资源
    最近更新 更多