Search code examples
javajira

How to implement JWT authorization in addon REST Spring Atlassian Connect API?


I created plugin using

mvn archetype:generate -DarchetypeGroupId=com.atlassian.connect -DarchetypeArtifactId=atlassian-connect-spring-boot-archetype -DarchetypeVersion=1.5.1

atlassian-connect.json

{...
 "scopes": [
 "read", "write"
],
"authentication": {
 "type": "jwt"
 },
 "lifecycle": {
 "installed": "/installed",
 "uninstalled": "/uninstalled"
 },
 "enableLicensing": false,
 "modules": {
  "generalPages": [

  {
    "key": "comments",
    "location": "system.top.navigation.bar",
    "name": {
      "value": "Comments"
    },
    "url": "/rest/api",
    "conditions": [{
      "condition": "user_is_logged_in"
    }]
  }
]
  }
}

I am trying to access my API

 AJS.$.ajax({
                    url: "https://X.ngrok.io/rest/api",
                    type: "GET",
                    dataType: "json",
                    contentType: "application/json",
                    async: false, headers: {
    'Authorization' : "JWT {{sessionToken}}"
},
                    success: function (data) {
                        console.log(e);
                    },
                    error: function(response) {

                        console.log(response);
                    }
                    })

How to get jwt on JS side (it is better to describe

simple plugin step by step, if u could (I checked many links with examples, but…))?


Solution

  • You are declaring an HTML page in your atlassian-connect.json file, i.e. the 'comments' general page. Hence, if someone opens this page, you can generate a JWT and inject it into the HTML document before returning it to the user/requester. Then you can use this JWT within your JavaScript code. Since you seem to be using the Spring Boot template, you should have a look at the section "Authenticating requests from iframe content back to the add-on" in the repositories readme file. This is exactly describing your case.

    The other option would be to generate a JWT based on a JWT you are receiving from the Connect application like Jira or Confluence. However, this is a bit more work to do. I can recommend to read about how to get a a valid JWT from the Connect application within JavaScript and also how the installation handshake phase works. Based on these you could generate your own JWT.

    However, in all cases, please take care that you won't generate a new token for each request, but rather for a session, so you can use the token for multiple requests. I recommend to go with option a), because it's already supported by the Sprint Boot Connect template.