使用Java中的OAuth创建Jira连接

时间:2016-10-06 07:19:32

标签: java oauth jira

我正在尝试使用OAuth在Jira中建立连接,并在连接成功后在Jira中创建问题。我现在有了访问令牌,我不知道如何传递该访问令牌以建立与Jira的连接。

这是我的代码,用于获取令牌,令牌密钥,检索请求令牌URL和访问令牌

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;
    }

以下是获取访问令牌的方法

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;
    }

这些方法给了我

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

现在我想使用这些进行jira连接。以前我使用基本身份验证来创建Jira连接,但现在我想使用Oauth创建Jira连接。这是我使用基本身份验证进行Jira连接的代码。任何人都可以让我知道如何调整代码或提供任何其他方法,我可以使用OAuth进行Jira连接。

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;
    }

2 个答案:

答案 0 :(得分:0)

3天的研究我终于破解了使用OAuth在Jira中创建,更新和删除问题的解决方案。对于使用OAuth在Jira中创建操作,将json数据作为输入流的形式传递,因为makeAuthenticatedRequest将参数作为(String url,String accessToken,InputStream bodyAsStream,String operationType)。请参阅下面的代码以获得更多参考。

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;

    }

对于所有获取操作,makeAuthenticatedRequest方法发生了变化。

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);
    }

有关更多参考,您可以参考rest-oauth-client-1.0.one-jar。在java反编译器中打开这个jar,看看类AtlassianOAuthClient.class,JIRAOAuthClient.class,TokenSecretVerifierHolder.class。这将使您完全理解我是如何实现上述方法的。

答案 1 :(得分:0)

只需获取项目 https://github.com/blackducksoftware/jira-oauth-sample 您将在几分钟内拥有一个工作版本。

对于您也可以使用它的帖子,我必须创建一个新方法,该方法不在捆绑包中,但几分钟后就会像魅力一样发挥作用。

我花了几天时间在 jira xray 中浏览了关于这个 oauth 1.0 舞蹈的很多东西,但没有一个是开箱即用的。

所以我奉基督的名和慷慨奉献。请不要删除这很重要!

enter image description here