0
votes

By using the following curl command i am able to access token and getting following response curl username:password@machinename:11002/appName/oauth/token -d grant_type=password -d username=loginFormUserID -d password=loginFormUserPassword

Response: { "entity_id" : 9, "entity_type" : "", "refresh_token" : "eyJhbGciOiJSUzI1NiJ9.", "scope" : "login", "expires_in" : 3599, "entity_name" : "name", "access_token" : "eyJhbGciOiJSUzI1NiJ9.ey", "token_type" : "bearer" }

if i will use spring OAuth2RestTemplate i am getting access denied,Here is my code details

    ResourceOwnerPasswordAccessTokenProvider provider = new ResourceOwnerPasswordAccessTokenProvider();
    ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
    resource.setClientAuthenticationScheme(AuthenticationScheme.form);
    resource.setAccessTokenUri("http://machinename:11002/appName/oauth/token");
    resource.setClientId("loginFormUserID");
    resource.setClientSecret("loginFormUserPassword");
    resource.setGrantType("password");
    resource.setUsername("username");
    resource.setPassword("password");
    OAuth2AccessToken accessToken = provider.obtainAccessToken(resource, new DefaultAccessTokenRequest());
    OAuth2RestTemplate restTemplateQ     = new OAuth2RestTemplate(resource, new DefaultOAuth2ClientContext(accessToken));
    System.out.println( restTemplateQ.getAccessToken());

Exception in thread "main" error="access_denied", error_description="Error requesting access token." at org.springframework.security.oauth2.client.token.OAuth2AccessTokenSupport.retrieveToken(OAuth2AccessTokenSupport.java:145) at org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordAccessTokenProvider.obtainAccessToken(ResourceOwnerPasswordAccessTokenProvider.java:47) at com.copart.g1.seller.middleware.client.RestTemplateTest.main(RestTemplateTest.java:55) Caused by: org.springframework.web.client.HttpClientErrorException: 401 Unauthorized at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91) at org.springframework.security.oauth2.client.token.OAuth2AccessTokenSupport$AccessTokenErrorHandler.handleError(OAuth2AccessTokenSupport.java:244) at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:641) at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:597) at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:565) at org.springframework.security.oauth2.client.token.OAuth2AccessTokenSupport.retrieveToken(OAuth2AccessTokenSupport.java:137) ... 2 more

1

1 Answers

1
votes

you need to remove resource.setClientAuthenticationScheme(AuthenticationScheme.form); the correct form is AuthenticationScheme.header

The class ResourceOwnerPasswordResourceDetails extends BaseOAuth2ProtectedResourceDetails, if you see this class the value is AuthenticationScheme.header

Thanks