How to get an auth code using ASWebAuthenticationSession?

Viewed 6384

I'm trying to obtain an auth code from Stripe's OAuth endpoint using ASWebAuthenticationSession - this event happens after the my Stripe redirect url gets called.

Unfortunately, the authSession's completion handler doesn't call back with a callbackURL. And I need this callbackURL to query the auth code. I've read different articles on this topic but I can't figure out why my implementation doesn't work they way I expect it to.

Here's my code:


class CreateStripeConnectAccountController: UIViewController {

  var authSession: ASWebAuthenticationSession!

  override func viewDidLoad() {
      super.viewDidLoad()
      configureAuthSession()
  }

  private func configureAuthSession() {

    let urlString = Constants.URLs.stripeConnectOAuth // Sample URL

    guard let url = URL(string: urlString) else { return }

    let callbackScheme = "myapp:auth"    

    authSession = ASWebAuthenticationSession(url: url, callbackURLScheme: callbackScheme, completionHandler: { (callbackURL, error) in
       guard error == nil, let successURL = callbackURL else {
          print("Nothing")
          return
       }

       let oauthToken = NSURLComponents(string: (successURL.absoluteString))?.queryItems?.filter({$0.name == "code"}).first

       print(successURL.absoluteString)
    })

    authSession.presentationContextProvider = self
    authSession.start()
  }
}

extension CreateStripeConnectAccountController: ASWebAuthenticationPresentationContextProviding {
    func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
        self.view.window ?? ASPresentationAnchor()
    }
}
4 Answers

I believe the issue is that you are giving nil for callbackURLScheme. You need to give a URL scheme that redirects to your app:

See apple's authentication example: https://developer.apple.com/documentation/authenticationservices/authenticating_a_user_through_a_web_service

And here's apple's docs on how to create a custom URL scheme for your app: https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app.

I know it's old, but anyway. Make sure, that callbackScheme and scheme that is used in redirect_uri are the same.

Your callbackScheme myapp:auth is incorrect format.

The symbol : cannot be used in the scheme name of a URI.

See the following RFC definition of Scheme.

Scheme names consist of a sequence of characters beginning with a letter and followed by any combination of letters, digits, plus ("+"), period ("."), or hyphen ("-").

https://datatracker.ietf.org/doc/html/rfc3986#section-3.1

Thefore, revising the callbackURLscheme as myapp-auth or myapp.auth works well.

try setting your callbackScheme = "myapp" to receive callback

and from your server-side it should return "myapp://auth?token=1234"

Hope it helps.

Related