Warm tip: This article is reproduced from serverfault.com, please click

ios-带有redirectURI的Swift OAuth2.0

(ios - Swift OAuth2.0 with redirectURI)

发布于 2020-11-16 18:26:53

我正在使用提供OAuth2.0身份验证的服务。这是我需要的步骤:

  • 使用用户ID作为参数打开URL
  • 用户批准我的应用(已正确注册)。
  • 将用户重定向到RedirectUri,并在哈希中包含访问令牌。

第三点是我的主要问题。

我已经使用Microsoft库实现了OAuth,并且一切正常。但是我不能在这里使用它们,因此我正在尝试https://github.com/OAuthSwift/OAuthSwift

这是我的代码:

private func authenticationService() {
    // create an instance and retain it
    let oauthswift = OAuth2Swift(
        consumerKey:    "xx",
        consumerSecret: "xxx",
        authorizeUrl:   "//myurl + userId",
        responseType:   "token"
    )

    oauthswift.authorizeURLHandler = OAuthSwiftOpenURLExternally.sharedInstance

    let handle = oauthswift.authorize(
        withCallbackURL: "???",
        scope: "", state:"") { result in
        switch result {
        case .success(let (credential, response, parameters)):
          print(credential.oauthToken)
          // Do your request
        case .failure(let error):
          print(error.localizedDescription)
        }
    }
}

这可以正确打开我的Safari,但随后我被重定向到哈希中带有访问令牌的URI,没有任何反应。

这里的主要问题是我有一个重定向uri,所以我想未调用回调URL?这不是打开工作表,而是重定向到Safari。我不喜欢这种方法。

如何通过上述步骤快速执行OAuth2.0?如何从URL获取访问令牌?最好的图书馆是什么?如何充分利用它?


更新:

这是我的stackExchange代码:

    let request: OAuth2Request = .init(authUrl: "https://stackexchange.com/oauth/dialog?client_id=<MYCLIENTID>&scope=private_info&redirect_uri=https://stackexchange.com/oauth/login_success",
                                   tokenUrl: "https://stackoverflow.com/oauth/access_token/json",
                                   clientId: "<MYCLIENTID>",
                                   redirectUri: "https://stackexchange.com/oauth/login_success",
                                   clientSecret: "",
                                   scopes: [])

堆栈应用程序中的OAuth域是=> stackexchange.com,因此我在URL中添加了以下内容:redirect-uri:// <stackexchange.com>(甚至没有<>)

但是,每次我批准我的应用程序时,我都会堆积在包含我的令牌的“授权应用程序”中,并且我不会被重定向。

Questioner
manubrio
Viewed
0
Hadi 2020-12-09 01:33:49

如果你以iOS 13为目标,则可以使用Apple提供的新AuthenticationServices库。

它可以在macOS和iOS上运行。

也许这会对其他开发人员有所帮助,我创建了一个简单的小型swift包来处理Swift中的OAuth2,你可以检查演示项目是否运行良好👍

https://github.com/hadiidbouk/SimpleOAuth2

编辑:

你传递的网址错误,它们应该像这样

let request: OAuth2Request = .init(authUrl: "https://stackoverflow.com/oauth",
                                       tokenUrl: "https://stackoverflow.com/oauth/access_token/json",
                                       clientId: "<<your client id>>",
                                       redirectUri: "redirect-uri://stackexchange.com",
                                       clientSecret: "<<your client secret>>",
                                       scopes: ["private_info"])