gdogaru
gdogaru

Reputation: 521

How to manually set access tokens on OAuthRestTemplate, spring-security-oauth?

I am trying to call an api that uses Oauth 1a using OAuthRestTemplate from spring-security-oauth.

I saw that most of the examples set the consumer key and secret and then let the library get the access tokens. I have the token and the token secret (which do not expire) and I want to set them on the OAuthRestTemplate and make calls, without going through the authentication flow.

Is that possible? if so, how?

Upvotes: 3

Views: 2260

Answers (2)

bly
bly

Reputation: 1592

This is possible, though a bit hacky. Example code below:

    // Assume you have a preconfigured RestTemplate
    OAuthRestTemplate template = new OAuthRestTemplate(resource);

    OAuthConsumerToken accessToken = new OAuthConsumerToken();
    accessToken.setAccessToken(true);
    accessToken.setResourceId(template.getResource().getId());
    accessToken.setValue(ACCESS_TOKEN);

    OAuthSecurityContextImpl securityContext = new OAuthSecurityContextImpl();
    securityContext.setAccessTokens(new HashMap<>());
    securityContext.getAccessTokens().put(accessToken.getResourceId(), accessToken);

    OAuthSecurityContextHolder.setContext(securityContext);

Ideally, you should check whether an existing security context exists, and add the token to the map if it's not already present.

Upvotes: 2

Dave Syer
Dave Syer

Reputation: 58094

AFAIK that's not possible (it is on the OAuth2 side but OAuth1 never got as much love). Contributions gratefully accepted.

Upvotes: 2

Related Questions