Create dynamic web hook for Jira, connect Spring boot

285 views Asked by At

I am attempting to register a web hook to my Jira cloud instance and I am following their documentation but I have not been able to make it work.

Specifically the section: Making API requests to the product as the add-on:

atlassianHostRestClients.authenticatedAsAddon(AddonAuthenticationType.OAUTH2).getForObject("/rest/api/example", Void.class);

My issue is when I run it I get an error:

401 Unauthorized: "{"message":"Client must be authenticated to access this >resource.","status-code":401}"

Now, I know I am not authenticated, but atlassianHostRestClients object, which according to their documentation:

atlassian-connect-spring-boot will automatically sign requests from your add-on to an >installed host product with JSON Web Tokens. To make a request, just autowire an > AtlassianHostRestClients object into your class.

So, anyone has experience with this that could help?

1

There are 1 answers

0
superodde On

I do this using and have a generic function in my class JiraApiHelpers.kt:

class JiraApiHelpers(
    internal val atlassianRestClient: AtlassianHostRestClients
) {
    fun <T: Any>getRequest(url: String, host: AtlassianHost, clazz: KClass<T>): T {
        return atlassianRestClient.authenticatedAsAddon(host).getForObject(url, clazz.java)
            ?: throw Exceptions.InvalidJiraApiRequestException(url, host)
    }
}

This let me format the returned object to given data class:

val issueData = jiraApiHelpers.getRequest(urlField, hostUser.host, JiraIssueData::class)

Here hostUser origins from my controller which is called by the webhook:

@PostMapping("/webhook")
fun calculateEstimatedEndTime(
    @RequestBody issueEvent: JiraIssueEvent,
    @AuthenticationPrincipal hostUser: AtlassianHostUser

This is implemented in a connect-app where the webhook is defined within the app in atlassian-connect.json:

"webhooks": [
  {
    "event": "jira:issue_updated",
    "url": "/webhook",
    "excludeBody": false
  }
]

To test your scenario I removed host from my call to Jira API and it worked as expected:

atlassianRestClient.authenticatedAsAddon().getForObject(url, clazz.java)

I see in the documentation you linked to, that the use of AddonAuthenticationType.OAUTH2 is limited to Connect-on-Forge apps. Maybe that is why you get 401.