I'm learning OAuth2 and I have problems with client_credentials grant configuration. Here is some client-server example.
Client side (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";
}
}
Resource server side (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);
}
}
When I hit client's /getServer, I get this exception:
org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException: Invalid token does not contain resource id (oauth2-resource)
If I remove ServerSecurity, ClientController works without throwing an exception, but server's actuator/health fails with 401.
What may be wrong?
ADDITIONAL INFO:
client's 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
server's yml:
server:
port: 8081
security:
oauth2:
client:
clientId: __data__
clientSecret: __data__
resource:
tokenInfoUri: https://dev-410899.oktapreview.com/oauth2/default/v1/introspect
答案 0 :(得分:0)
默认的OAuth2资源服务器ID为oauth2-resource
。 (检查ResourceServerSecurityConfigurer
)。
您可以设置自定义资源服务器ID:
@Override
public void configure(ResourceServerSecurityConfigurer oauthServer) {
oauthServer
.resourceId("your resource id");
}
发布令牌时,您必须确保让client_credentials用户能够访问正确的资源服务器ID。