2

I am trying to make connection in Jira using OAuth and create an issue in Jira after the connection is successfull. I have got the access token now I dont know how to pass that access token to make connection to Jira.

Here is my code to get Token, Token secret, Retrieved request token URL and Access Token

private AtlassianOAuthClient getJiraOAuthClient() {

        final String baseURI = "http://bmh1060149:8080";
        final String consumerKey = "hardcoded-consumer";
        final String consumerPrivatekey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDFkPMZQaTqsSXI+bSI65rSVaDzic6WFA3WCZMVMi7lYXJAUdkXo4DgdfvEBO21Bno3bXIoxqS411G8S53I39yhSp7z2vcB76uQQifi0LEaklZfbTnFUXcKCyfwgKPp0tQVA+JZei6hnscbSw8qEItdc69ReZ6SK+3LHhvFUUP1nLhJDsgdPHRXSllgZzqvWAXQupGYZVANpBJuK+KAfiaVXCgA71N9xx/5XTSFi5K+e1T4HVnKAzDasAUt7Mmad+1PE+56Gpa73FLk1Ww+xaAEvss6LehjyWHM5iNswoNYzrNS2k6ZYkDnZxUlbrPDELETbz/n3YgBHGUlyrXi2PBjAgMBAAECggEAAtMctqq6meRofuQbEa4Uq5cv0uuQeZLV086VPMNX6k2nXYYODYl36T2mmNndMC5khvBYpn6Ykk/5yjBmlB2nQOMZPLFPwMZVdJ2Nhm+naJLZC0o7fje49PrN2mFsdoZeI+LHVLIrgoILpLdBAz/zTiW+RvLvMnXQU4wdp4eO6i8J/Jwh0AY8rWsAGkk1mdZDwklPZZiwR3z+DDsDwPxFs8z6cE5rWJd2c/fhAQrHwOXyrQPsGyLHTOqS3BkjtEZrKRUlfdgV76VlThwrE5pAWuO0GPyfK/XCklwcNS1a5XxCOq3uUogWRhCsqUX6pYfAVS6xzX56MGDndQVlp7U5uQKBgQDyTDwhsNTWlmr++FyYrc6liSF9NEMBNDubrfLJH1kaOp590bE8fu3BG0UlkVcueUr05e33Kx1DMSFW72lR4dht1jruWsbFp6LlT3SUtyW2kcSet3fC8gySs2r6NncsZ2XFPoxTkalKpQ1atGoBe3XIKeT8RDZtgoLztQy7/7yANQKBgQDQvSHEKS5SttoFFf4YkUh2QmNX5m7XaDlTLB/3xjnlz8NWOweK1aVysb4t2Tct/SR4ZZ/qZDBlaaj4X9h9nlxxIMoXEyX6Ilc4tyCWBXxn6HFMSa/Rrq662Vzz228cPvW2XGOQWdj7IqwKO9cXgJkI5W84YtMtYrTPLDSjhfpxNwKBgGVCoPq/iSOpN0wZhbE1KiCaP8mwlrQhHSxBtS6CkF1a1DPm97g9n6VNfUdnB1Vf0YipsxrSBOe416MaaRyUUzwMBRLqExo1pelJnIIuTG+RWeeu6zkoqUKCAxpQuttu1uRo8IJYZLTSZ9NZhNfbveyKPa2D4G9B1PJ+3rSO+ztlAoGAZNRHQEMILkpHLBfAgsuC7iUJacdUmVauAiAZXQ1yoDDo0Xl4HjcvUSTMkccQIXXbLREh2w4EVqhgR4G8yIk7bCYDmHvWZ2o5KZtD8VO7EVI1kD0z4Zx4qKcggGbp2AINnMYqDetopX7NDbB0KNUklyiEvf72tUCtyDk5QBgSrqcCgYEAnlg3ByRd/qTFz/darZi9ehT68Cq0CS7/B9YvfnF7YKTAv6J2Hd/i9jGKcc27x6IMi0vf7zrqCyTMq56omiLdu941oWfsOnwffWRBInvrUWTj6yGHOYUtg2z4xESUoFYDeWwe/vX6TugL3oXSX3Sy3KWGlJhn/OmsN2fgajHRip0=";

        AtlassianOAuthClient jiraoAuthClient = new AtlassianOAuthClient(consumerKey, consumerPrivatekey, baseURI, "");

        return jiraoAuthClient;
    }

Here is a method to get access token

private String getAccessToken() {

        AtlassianOAuthClient jiraoAuthClient = getJiraOAuthClient();
        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);

        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 accessToken = jiraoAuthClient.swapRequestTokenForAccessToken(token, tokenSecret, "");
        // String verifier = requestToken.verifier;
        System.out.println("Access token is : " + accessToken);
        return accessToken;
    }

These methods are giving me

Token is 38ESi9IJW5u3vKDslPFtuV1ZtzDpr6zi
Token secret is cnDSL8oJyuoaQdRcFDwgHzLppSshQn9b
Retrieved request token. go to http://bmh1060149:8080/plugins/servlet/oauth/authorize?oauth_token=38ESi9IJW5u3vKDslPFtuV1ZtzDpr6zi
Access token is : 015CeJiH8cpI5R3OKpNco158kApq8YwV

Now I want to make jira connection using these. Previously I was using basic authentication to create Jira connection but now I want to create Jira connection using Oauth. Here is my code to make Jira connection using Basic authentication. Can anyone please let me know how to tweak the code or else provide any other method by which I can make Jira connection using OAuth.

public String jiraConnectionpost(String auth, String url, String key) throws JSONException {

        System.out.println("Inside jiraConnectionpost for JiraAdapterImpl");

        WebResource webResource = client.resource(url);
        ClientResponse response = webResource.header("Authorization", "Basic " + auth).type("application/json")
                .accept("application/json").post(ClientResponse.class, key);
        int statusCode = response.getStatus();

        if (statusCode == 401) {
            try {
                throw new AuthenticationException("Invalid Username or Password");
            } catch (AuthenticationException e) {
                e.printStackTrace();
            }
        }
        String jsonString = response.getEntity(String.class);

        url = null;
        return jsonString;
    }
SharpC
  • 6,974
  • 4
  • 45
  • 40
Harshad Holkar
  • 511
  • 5
  • 16

2 Answers2

0

3 days of research I finally cracked the solution to create, update and delete issue in Jira using OAuth. For create operation in Jira using OAuth pass your json data as a form of input stream because makeAuthenticatedRequest takes parameter as (String url, String accessToken, InputStream bodyAsStream, String operationType). Please see the code below for more refrence.

public void createJiraIssue(JiraExecutionDTO jiraEx) {

        System.out.println("Inside createJiraIssue for JiraAdapterImpl");

        String jiraUrl = jiraEx.getJiraUrl();

        String operationType = "CREATE";

        String jSonData = "Your Json data for create operation";
        try {
            InputStream inputStream = new ByteArrayInputStream(jSonData.getBytes("UTF-8"));
            OAuthMessage response = getResponseForRequest(jiraUrl, inputStream, operationType);
            System.out.println(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

private OAuthMessage getResponseForRequest(String url, InputStream inputstream, String operationType) {

        AtlassianOAuthClientRequest jiraOauthClient = getJiraOAuthClient();
        String accessToken = getAccessToken();
        OAuthMessage response = null;
        try {
            response = jiraOauthClient.makeAuthenticatedRequest(url, accessToken, inputstream, operationType);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

public OAuthMessage makeAuthenticatedRequest(String url, String accessToken, InputStream bodyAsStream,
            String operationType) throws Exception {

        //boolean suppressNPE = false;
        String method = null;

        OAuthAccessor accessor = getAccessor();
        OAuthClient client = new OAuthClient(new HttpClient4());
        accessor.accessToken = accessToken;
        OAuthMessage request = null;
        if (operationType == "CREATE") {
            method = OAuthMessage.POST;
            request = accessor.newRequestMessage(method, url, Collections.<Map.Entry<?, ?>> emptySet(), bodyAsStream);
        } else if (operationType == "UPDATE") {
            method = OAuthMessage.PUT;
            request = accessor.newRequestMessage(method, url, Collections.<Map.Entry<?, ?>> emptySet(), bodyAsStream);
        } else if (operationType == "DELETE") {
            method = OAuthMessage.DELETE;
            request = accessor.newRequestMessage(method, url, Collections.<Map.Entry<?, ?>> emptySet());
        }
        List<Map.Entry<String, String>> headers = request.getHeaders();
        headers.add(new OAuth.Parameter(HttpMessage.CONTENT_TYPE, "application/json"));
        // headers.add(new OAuth.Parameter(HttpMessage.CONTENT_LENGTH,
        // contentLength));
        OAuthMessage response = client.invoke(request, ParameterStyle.QUERY_STRING);

        return response;

    }

For All Get Operation there is a change in makeAuthenticatedRequest method.

public String makeAuthenticatedRequest(String url, String accessToken) {
        try {
            OAuthAccessor accessor = getAccessor();
            OAuthClient client = new OAuthClient(new HttpClient4());
            accessor.accessToken = accessToken;
            OAuthMessage response = client.invoke(accessor, url, Collections.<Map.Entry<?, ?>> emptySet());
            return response.readBodyAsString();
        } catch (Exception e) {
            throw new RuntimeException("Failed to make an authenticated request.", e);
        }
    }

public void getAllIssueTypes(JiraExecutionDTO jcqcred) {

        System.out.println("Inside getAllIssuetypeAssociatedToProject for JiraAdapterImpl");

        String jiraURL = jcqcred.getJiraUrl();
        if (!jiraURL.endsWith("/")) {
            jiraURL = jiraURL + "/";
        }

        String url = jiraURL + "rest/api/2" + "/" + "issuetype";

        String issueTypes = getResponseForRequest(url);

        System.out.println("Issuetype associated to project are\n" + issueTypes);
    }

For more refrence you can refer to rest-oauth-client-1.0.one-jar. Open this jar in java decompiler and see classes AtlassianOAuthClient.class, JIRAOAuthClient.class, TokenSecretVerifierHolder.class. This will give you complete understanding how I have implemented the above methods.

Harshad Holkar
  • 511
  • 5
  • 16
  • I've been trying to create a connection using oAuth. I am getting the accessor as null at the line OAuthAccessor accessor = getAccessor(); Please tell what must have gone wrong with the JIRA accessor. – BIndu_Madhav Nov 10 '17 at 10:26
  • Hi Bindu .... you have to go inside getAccessor() method and have to debug it to get to know whats wrong with oauth connection – Harshad Holkar Nov 11 '17 at 05:59
  • how did you got this consumerkey value? – Saurabh Garg Mar 23 '18 at 06:22
0

Just get the project https://github.com/blackducksoftware/jira-oauth-sample and you'll have a working version in minutes.

For posts you can using it too, I had to create a new method that's not in the bundle but that will work like a charm after a few minutes.

I spent several days browsing a lot of things around this oauth 1.0 dance in jira xray and none of them worked out of the box.

So I am offering this in Christ's Name and Generosity. Please do not remove this it is important !

enter image description here