我正在使用提供 OAuth2.0 身份验证的服务。这是我需要的步骤:
- 打开一个以用户 ID 作为参数的 URL
- 用户批准我的应用程序(已注册正确)。
- 用户被重定向到一个 RedirectUri,在哈希中带有访问令牌。
第三点是我的主要问题。
我已经用微软库实现了 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>(即使没有 <>)
但是每次我批准我的应用程序时,我都会堆叠在包含我的令牌的“授权应用程序”中,并且我没有被重定向。