Spring и OAuth2 в неинтерактивном режиме с типом предоставления client_credentials
У меня есть служба REST, которая использует аутентификацию OAuth2 и предоставляет конечную точку для запроса токена с типом предоставления client_credentials. Приложение основано на Spring Boot.
Пока я понял, что могу запросить токен с чем-то вроде:
@SpringBootApplication
@EnableOAuth2Client
public class App extends WebSecurityConfigurerAdapter {
@Autowired
OAuth2ClientContext oauth2ClientContext;
//...
@Override
protected void configure(HttpSecurity http) throws Exception {
// Does nothing - to allow unrestricted access
}
@Bean
protected OAuth2RestTemplate myTemplate() {
ClientCredentialsResourceDetails details = new ClientCredentialsResourceDetails();
details.setAccessTokenUri("http://localhost:8080/oauth/token");
details.setClientId("theClient");
details.setClientSecret("thePassword");
return new OAuth2RestTemplate(details, oauth2ClientContext);
}
}
@RestController
public class TestController {
@Autowired
OAuth2RestTemplate myTemplate;
@RequestMapping("/token")
private String getToken() {
return myTemplate.getAccessToken().getValue();
}
}
И это почти работает, но всякий раз, когда я звоню /token
конечная точка, есть исключение:
org.springframework.security.authentication.InsufficientAuthenticationException: Authentication is required to obtain an access token (anonymous not allowed)
at org.springframework.security.oauth2.client.token.AccessTokenProviderChain.obtainAccessToken(AccessTokenProviderChain.java:88) ~[spring-security-oauth2-2.0.9.RELEASE.jar:na]
at org.springframework.security.oauth2.client.OAuth2RestTemplate.acquireAccessToken(OAuth2RestTemplate.java:221) ~[spring-security-oauth2-2.0.9.RELEASE.jar:na]
at org.springframework.security.oauth2.client.OAuth2RestTemplate.getAccessToken(OAuth2RestTemplate.java:173) ~[spring-security-oauth2-2.0.9.RELEASE.jar:na]
...
Здесь выдается исключение, но я не уверен, как заставить Spring использовать контекстную аутентификацию, отличную от AnonymousAuthenticationToken
, На самом деле, я не хочу никакой аутентификации от клиента, потому что анонимный - это нормально. Как мне этого добиться?