Search code examples
iosswiftoauth-2.0authorizationreddit

Reddit API returns 401 (using OAuthSwift)


So i am trying get my sample reddit app working with OAuthSwift

I am getting 401 and Unauthorized from reddit

oauthswift = OAuth2Swift(
     consumerKey:    "reddit_Client_id",
     consumerSecret: "",
     authorizeUrl:   "https://www.reddit.com/api/v1/authorize",
     accessTokenUrl: "https://www.reddit.com/api/v1/access_token",
     responseType:   "code"
)
    
guard let rwURL = URL(string: "redditTestApp://oauth-callback") else { return }
    
handle = oauthswift!.authorize(
        withCallbackURL: rwURL,
        scope: "identity read", state:"reddit") { result in
        switch result {
        case .success(let (credential, response, parameters)):
          print(credential.oauthToken)
          // Do your request
        case .failure(let error):
            print(error.description)
        }
}

I am kinda lost on what i am missing here. I think i have passed all the parameters and not sure what is left for the reason to get an unauthorized response.


Solution

  • So leaving it here just in case somebody in future needs help.

    The problem was that during retrieving the access token reddit requires an authorization header with http basic auth.

    The OAuthSwift library provides an easy way to do this you just need to add

    oauthswift?.accessTokenBasicAuthentification = true

    and you are done.