Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an auth code using ASWebAuthenticationSession?

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()
    }
}
like image 232
uchenna aguocha Avatar asked Oct 16 '22 05:10

uchenna aguocha


1 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.

like image 159
johnny kehr Avatar answered Nov 15 '22 14:11

johnny kehr