Getting 401 error when getting cloud ID

I’m developing a Mac/iOS app that works with Jira’s REST API and uses OAuth authorization. I’m able to get an access token from Jira. To make API calls I must get the cloud ID using the access token. I have the following Swift code to get the cloud ID:

func getCloudID() async -> String {
        // Build the URL
        var components = URLComponents()
        components.scheme = "https"
        components.host = "api.atlassian.com"
        components.path = "/oauth/token/accessible-resources"
        var request = URLRequest(url: components.url!)
        
        guard let accessToken = getAccessToken() else {
            return ""
        }
        
        // Encode the token and build the header
        guard let encodedTokenString = accessToken.data(using: .utf8)?.base64EncodedString() else { fatalError("Can't encode token") }
        let authString = String("Bearer \(encodedTokenString)")
        request.addValue(authString, forHTTPHeaderField: "Authorization")
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        
        // Make the call to get the cloud ID
        do {
            let (data, _) = try await URLSession.shared.data(for: request, delegate: nil)
            let dataString = String(data: data, encoding: .utf8)
            let decoder = JSONDecoder()
            let cloudDictionary = try decoder.decode(JiraCloudID.self, from: data)
            return cloudDictionary.id
        } catch {
            return ""
        }   
    }

The access token is valid, but I get a 401 error when making the call. The 401 error persists with a fresh token. I added the dataString variable to show the JSON string Jira returns, and it has the following value:

"{\"code\":401,\"message\":\"Unauthorized\"}"

The access token has the following scopes:

read:jira-user 
read:jira-work 
manage:jira-configuration 
manage:jira-project 
write:jira-work 
offline_access

What do I have to do to fix the 401 error?

1 Like

Welcome to the Atlassian developer community @meandmark,

I think the problem is that you are base64 encoding the Bearer token. Did you find that in the docs or example code somewhere?

1 Like

Base64 encoding the token was the problem. Using the access token removed the 401 error. Thanks.

The base64 encoding was from code that used a personal access token instead of an OAuth access token.

1 Like