Spring OAuth2: How do I allow password grant type using java configuration?

柔情痞子 提交于 2020-12-13 11:35:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!