问题
In my java server application, I get the following error when trying to authenticate using the password grant flow:
TokenEndpoint - Handling error: InvalidClientException, Unauthorized grant type: password
I did allow the grant explicitly for the user in question:
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("officialclient")
.authorizedGrantTypes("authorization_code, refresh_token, password")
.authorities("ROLE_CLIENT")
.scopes("read", "write")
.resourceIds(RESOURCE_ID)
.secret("officialclientsecret")
.redirectUris("https://www.someurl.com/")
}
I am using the following code to retrieve the access token:
ResourceOwnerPasswordResourceDetails resourceDetails = new ResourceOwnerPasswordResourceDetails();
resourceDetails.setClientAuthenticationScheme(AuthenticationScheme.header);
resourceDetails.setAccessTokenUri("http://localhost:8080/organizer/oauth/token");
resourceDetails.setScope(Arrays.asList("read", "write"));
resourceDetails.setId("resource");
resourceDetails.setClientId("officialclient");
resourceDetails.setClientSecret("officialclientsecret");
resourceDetails.setUsername("Paul");
resourceDetails.setPassword("password");
OAuth2RestTemplate template = new OAuth2RestTemplate(resourceDetails, context);
return template.getAccessToken().getValue();
Is there a global setting for allowing the password grant type?
回答1:
You should use Variable Arguments, not comma separated string value, as you did:
.authorizedGrantTypes("authorization_code, refresh_token, password")
Replace it with:
.authorizedGrantTypes("authorization_code", "refresh_token", "password")
回答2:
You need to provide an AuthenticationManager
to the AuthorizationServerEndpointsConfigurer
. More info here under Grant Types. Example:
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
If you want to use the default manager provided by spring boot for development purposes, you can grab the bean like this:
@Component
@EnableAuthorizationServer
public class MyAuthorizationServerConfigurer extends AuthorizationServerConfigurerAdapter {
private final AuthenticationManager authenticationManager;
public MyAuthorizationServerConfigurer(AuthenticationConfiguration authenticationConfiguration) throws Exception {
this.authenticationManager = authenticationConfiguration.getAuthenticationManager();
}
}
来源:https://stackoverflow.com/questions/35829801/spring-oauth2-how-do-i-allow-password-grant-type-using-java-configuration