Ashwini
Ashwini

Reputation: 71

How to get Access Token in java using OAuth 1.0?

Requirement: I want to access resources reside in cloud application.

This cloud application provided me following details to access resources through OAuth 1.0 authentication.

OAuth Credentials

  1. Consumer Key
  2. Consumer Secret

OAuth Request URLs

1. Request Token URL
2. Authorise URL
3. Access Token URL
4. API Endpoint URL

I have wrote following java code to get Request Token and Request Token Secret . I store Request Token and Secret in property file for retrieving Access Token.

OAuthAccessor accessor = createOAuthAccessor();
            OAuthClient client = new OAuthClient(new HttpClient4());
                client.getRequestToken(accessor);

 props.setProperty("requestToken", accessor.requestToken);
                props.setProperty("tokenSecret", accessor.tokenSecret);


 private OAuthAccessor createOAuthAccessor(){
        String consumerKey = props.getProperty("consumerKey");
        String callbackUrl = null;
        String consumerSecret = props.getProperty("consumerSecret");

        String reqUrl = props.getProperty("requestUrl");
        String authzUrl = props.getProperty("authorizationUrl");
        String accessUrl = props.getProperty("accessUrl");

        OAuthServiceProvider provider
                = new OAuthServiceProvider(reqUrl, authzUrl, accessUrl);
        OAuthConsumer consumer
                = new OAuthConsumer(callbackUrl, consumerKey,
                consumerSecret, provider);
        return new OAuthAccessor(consumer);
    }

Property file details:

requestToken= generated by service provider
authorizationUrl= Authorise URL provided by cloud application
consumerSecret= Consumer Secret provided by cloud application
accessUrl=Access Token URL provided by cloud application
tokenSecret= generated by service provider
requestUrl= Request Token URL provided by cloud application
consumerKey= Consumer Secret provided by cloud application
appName= API Endpoint URL provided by cloud application

I am able to retrieve Request Token and Request Token Secrete from Service Provider with Request Token URL provided by cloud application.

Then I used generated Request Token and Request Token Secrete to get Access Token by using following code

OAuthAccessor accessor = createOAuthAccessor();
accessor.tokenSecret = props.getProperty("tokenSecret");
OAuthClient client = new OAuthClient(new HttpClient4());
return client.invoke(accessor, "GET",  url, params);

After executing above code for retrieving Access token I got following exception

If I pass API Endpoint URL /Resource as value of URL parameter to client.invoke() in above code then I am getting following exception

> <<<<<<<< HTTP response: HTTP/1.1 401 Unauthorized Cache-Control:
> private Content-Type: text/html; charset=utf-8 WWW-Authenticate: OAuth
> Realm="115.248.52.162" X-S: 445759-O1VMAP02 Strict-Transport-Security:
> max-age=31536000 Date: Tue, 18 Jun 2013 06:59:28 GMT Content-Length:
> 142
> 
> Exception in thread "main" net.oauth.OAuthProblemException:
> token_rejected oauth_problem_advice: Token RZXHZYCCUMNMZA88032WJFB
> does not match an expected ACCESS token

And if I pass Access Token URL as value of URL parameter in client.invoke() then I am getting following exception

> <<<<<<<< HTTP response: HTTP/1.1 401 Unauthorized Cache-Control:
> private Content-Type: text/html; charset=utf-8 WWW-Authenticate: OAuth
> Realm="49.248.38.202" X-S: 445758-O1VMAP01 Strict-Transport-Security:
> max-age=31536000 Date: Tue, 18 Jun 2013 05:47:30 GMT Content-Length:
> 115
> 
> oauth_problem=permission_denied&oauth_problem_advice=The%20consumer%20was%20denied%20access%20to%20this%20resource.

Questions:

  1. Which URL Should I use to get Access Token?
  2. Am I missing any step or setting to retrieve Access token?

Thanks in Advance.

Upvotes: 4

Views: 6714

Answers (2)

Harshad Holkar
Harshad Holkar

Reputation: 541

Here is the java code to generate access token. I have integrated my generic application to Jira using OAuth Authentication. Here is the java code to access the using OAuth Authentication. Please include rest-oauth-client-1.0.one-jar jar in your application.

public static String getAccessToken(){  

    final String baseURI = "http://bmh1060149:8080";
    final String consumerKey = "hardcoded-consumer";
    final String consumerPrivatekey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDFkPMZQaTqsSXI+bSI65rSVaDzic6WFA3WCZMVMi7lYXJAUdkXo4DgdfvEBO21Bno3bXIoxqS411G8S53I39yhSp7z2vcB76uQQifi0LEaklZfbTnFUXcKCyfwgKPp0tQVA+JZei6hnscbSw8qEItdc69ReZ6SK+3LHhvFUUP1nLhJDsgdPHRXSllgZzqvWAXQupGYZVANpBJuK+KAfiaVXCgA71N9xx/5XTSFi5K+e1T4HVnKAzDasAUt7Mmad+1PE+56Gpa73FLk1Ww+xaAEvss6LehjyWH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DetopX7NDbB0KNUklyiEvf72tUCtyDk5QBgSrqcCgYEAnlg3ByRd/qTFz/darZi9ehT68Cq0CS7/B9YvfnF7YKTAv6J2Hd/i9jGKcc27x6IMi0vf7zrqCyTMq56omiLdu941oWfsOnwffWRBInvrUWTj6yGHOYUtg2z4xESUoFYDeWwe/vX6TugL3oXSX3Sy3KWGlJhn/OmsN2fgajHRip0=";

    AtlassianOAuthClient jiraoAuthClient = new AtlassianOAuthClient(consumerKey, consumerPrivatekey, baseURI, "");
    TokenSecretVerifierHolder requestToken = jiraoAuthClient.getRequestToken();
    String authorizeUrl = jiraoAuthClient.getAuthorizeUrlForToken(requestToken.token);
    String token = requestToken.token;
    String tokenSecret = requestToken.secret;
    System.out.println("Token is " + requestToken.token);
    System.out.println("Token secret is " + requestToken.secret);
    System.out.println("Retrieved request token. go to " + authorizeUrl);

The above code will give you token, tokenSecret and authorizeUrl. After getting the authorizeUrl, Paste the URL in the browser it will ask for allow and deny options. Allow it to generate the verification code. Ather the url is authorized the access token can be generated from the code below.

    URI uri=null;
    try {
        uri = new URI(authorizeUrl);
    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    if(Desktop.isDesktopSupported()){
        Desktop desktop = Desktop.getDesktop();
        try {
            desktop.browse(uri);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    String verifier = requestToken.verifier;

    String accessToken = jiraoAuthClient.swapRequestTokenForAccessToken(token, tokenSecret, verifier);
    System.out.println("Access token is : " + accessToken);
    return accessToken;
}

If you are also interested in accessing OAuth via command prompt you can also access it via there also. Here are the steps to access it via command prompt.

First create an application link. For that you can refer https://developer.atlassian.com/jiradev/jira-apis/jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-example-oauth-authentication

Download rest-oauth-client-1.0.one-jar.jar and rest-oauth-client-1.0-sources.jar and paste in your local drive. Access the following commands from there.

D:\OAuth Jars>java -jar rest-oauth-client-1.0.one-jar.jar requestToken "Your Jira base url"

Once you execute the above command you will get the Token, Token secret and Retrieved request token.

Token is iJKs7Sq4nI3tK0bTqBYSNNOt9rkwrKK9
Token secret is qimK5FibcAKD5ACbF2aKEPpiBWltgwET
Retrieved request token. go to http://bmh1060149:8080/plugins/servlet/oauth/authorize?oauth_token=iJKs7Sq4nI3tK0bTqBYSNNOt9rkwrKK9

Then you have to invoke the Retrieved request token url through the browser to get the verification code. It will ask you to allow or deny. If you click on allow it will give you verification code.

D:\OAuth Jars>java -jar rest-oauth-client-1.0.one-jar.jar accessToken "Your Jira base url" "iJKs7Sq4nI3tK0bTqBYSNNOt9rkwrKK9" "qimK5FibcAKD5ACbF2aKEPpiBWltgwET" "toYvZB"

This will give you the access token

Access token is : zGBqUzmwobyS0GFXrJMIs18lsAUd51Wb

Once you get the access token you can fetch the data from whatever url you will pass to it.

D:\OAuth Jars>java -jar rest-oauth-client-1.0.one-jar.jar request "zGBqUzmwobyS0GFXrJMIs18lsAUd51Wb" "Your Jira base url/rest/api/2/issue/NWFM-4"

Hope this helps

Upvotes: 1

ikumen
ikumen

Reputation: 11643

Without seeing your cloud api documentation, I can only assume they follow the typical oauth dance for authentication - which is:

  1. you get request token from provider (request token url)
  2. using request token, form an auth url (usually points to provider)
  3. redirect user to auth url (authorize url)
  4. user authenticates/authorizes
  5. provider does callback back to you with verifier
  6. using verifier and request token, you exchange for access token (access token url)
  7. now you can use your access token to access the api

So unless you're missing some of these steps, some other things to look at are: correctly signing request, using correct urls for each step, passing correct token at each step.

Also, the request token/secret is usually short lived, while the access token is "usually" much longer and in most cases/systems can be used with multiple api request.

Upvotes: 0

Related Questions