如何使用 ASWebAuthenticationSession 获取授权码?

uch*_*cha 8 oauth ios stripe-payments swift aswebauthenticationsession

我正在尝试使用 ASWebAuthenticationSession 从Stripe 的 OAuth 端点获取身份验证代码 - 此事件在调用我的 Stripe 重定向 url 后发生。

不幸的是,authSession 的完成处理程序不会使用callbackURL 进行回调。我需要这个callbackURL来查询授权码。我读过有关该主题的不同文章,但我不明白为什么我的实现没有按照我期望的方式工作。

这是我的代码:


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()
    }
}
Run Code Online (Sandbox Code Playgroud)

wil*_*lc0 5

我相信问题在于你正在nil付出callbackURLScheme。您需要提供一个重定向到您的应用程序的 URL 方案:

请参阅苹果的身份验证示例:https://developer.apple.com/documentation/authenticationservices/authenticating_a_user_through_a_web_service

以下是有关如何为应用程序创建自定义 URL 方案的 Apple 文档: 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