首页 > 解决方案 > 无效令牌不包含资源 id (oauth2-resource)

问题描述

我正在学习 OAuth2,但我在 client_credentials 授权配置方面遇到了问题。这是一些客户端-服务器示例。

客户端(8080):

@SpringBootApplication
@EnableOAuth2Client
public class ClientApplication {

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

    @Bean
    @ConfigurationProperties("security.oauth2.client")
    public ClientCredentialsResourceDetails oAuthDetails() {
        return new ClientCredentialsResourceDetails();
    }

    @Bean
    public OAuth2RestTemplate restTemplate() {
        return new OAuth2RestTemplate(oAuthDetails());
    }
}

@Configuration
public class ClientSecurity extends WebSecurityConfigurerAdapter {

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

@Controller
public class ClientController {

    @Autowired
    private OAuth2RestTemplate template;

    @GetMapping("/getServer")
    public String get() {
        template.getForEntity("http://localhost:8081/endpoint", String.class);
        return "index.html";
    }
}

资源服务器端(8081):

@SpringBootApplication
@EnableResourceServer
public class ServerApplication {

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

@Configuration
public class ServerSecurity extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/actuator/**").permitAll();
    }
}

@RestController
public class ServerController {

    @GetMapping("/endpoint")
    public ResponseEntity<String> respond() {
        return new ResponseEntity<>("", HttpStatus.OK);
    }
}

当我点击客户端的 /getServer 时,我得到了这个异常:

org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException: Invalid token does not contain resource id (oauth2-resource)

如果我删除 ServerSecurity,ClientController 可以正常工作而不会引发异常,但服务器的执行器/运行状况会因 401 而失败。

可能有什么问题?

附加信息:

客户的 yml:

server:
  port: 8080

security:
  oauth2:
    client:
      grant-type: client_credentials
      clientId: __data__
      clientSecret: __data__
      accessTokenUri: https://dev-410899.oktapreview.com/oauth2/default/v1/token
      scope: web_app
    resource:
      id: oauth2-resource

服务器的 yml:

server:
  port: 8081

security:
  oauth2:
    client:
      clientId: __data__
      clientSecret: __data__
    resource:
      tokenInfoUri: https://dev-410899.oktapreview.com/oauth2/default/v1/introspect

标签: javaspring-security-oauth2

解决方案


默认的 OAuth2 资源服务器 ID 是oauth2-resource. (检查ResourceServerSecurityConfigurer)。您可以设置自定义资源服务器 ID:

@Override
public void configure(ResourceServerSecurityConfigurer oauthServer) {
    oauthServer
            .resourceId("your resource id");
}

在发出令牌时,您必须确保让您的 client_credentials 用户访问正确的资源服务器 ID。


推荐阅读