我已经尝试了一段时间让oauth2与Untappd api(https://untappd.com/api/docs#authentication)一起工作,并且已经遇到了几个不同的oauth2框架。
我一直在尝试P2 OAuth。我似乎能够启动身份验证过程,用户登录,我得到一个代码并且遇到麻烦将代码发送回untappd以获取令牌。我已经从P2 oauth中脱离了这个例子:
class ViewController: UIViewController {
fileprivate var alamofireManager: SessionManager?
var loader: OAuth2DataLoader?
var oauth2 = OAuth2CodeGrantNoTokenType(settings: [
"client_id": "A0******************",
"client_secret": "BA******************",
"authorize_uri": "https://untappd.com/oauth/authenticate",
"token_uri": "https://untappd.com/oauth/authorize",
"redirect_uris": ["****://oauthcallback"],
"response_type": "code",
"secret_in_body": false,
"keychain": true,
] as OAuth2JSON)
@IBOutlet var imageView: UIImageView?
@IBOutlet var signInEmbeddedButton: UIButton?
@IBOutlet var signInSafariButton: UIButton?
@IBOutlet var signInAutoButton: UIButton?
@IBOutlet var forgetButton: UIButton?
@IBAction func signInEmbedded(_ sender: UIButton?) {
if oauth2.isAuthorizing {
oauth2.abortAuthorization()
return
}
sender?.setTitle("Authorizing...", for: UIControlState.normal)
oauth2.authConfig.authorizeEmbedded = true
oauth2.authConfig.authorizeContext = self
oauth2.verbose = true
oauth2.authorize() { authParameters, error in
if let params = authParameters {
print("Authorized! Access token is in `oauth2.accessToken`")
print("Authorized! Additional parameters: \(params)")
}
else {
print("Authorization was cancelled or went wrong: \(error)") // error will not be nil
}
}
}
在日志中,我似乎找回了代码,但最终的交换失败了:
[Debug] OAuth2:在https://untappd.com/oauth/authorize处为访问令牌交换代码2010D2 *********** 重定向
[Debug] OAuth2:交换了访问[false]和刷新[false]令牌的代码 授权!访问令牌位于
oauth2.accessToken
授权!其他参数:[" meta":{ " ERROR_DETAIL" ="缺少client_id,redirect_url,client_secret或代码参数。请再次检查您的请求。&#34 ;; " ERROR_TYPE" =" param_error&#34 ;; " HTTP_CODE" = 500; },"响应":< __ NSArray0 0x174005900>( ) ]
对于OAuth2和Swift 3似乎没什么帮助,除非我找错了地方。有任何想法吗?
答案 0 :(得分:0)
想出来了。如果有其他人遇到这个。原来只需要修改OAuth2CodeGrant类,添加到在代码交换令牌期间没有传递的client_secret中:
open func accessTokenRequest(with code: String, params: OAuth2StringDict? = nil) throws -> OAuth2AuthRequest {
guard let clientId = clientConfig.clientId, !clientId.isEmpty else {
throw OAuth2Error.noClientId
}
guard let redirect = context.redirectURL else {
throw OAuth2Error.noRedirectURL
}
guard let clientSecret = clientConfig.clientSecret else {
throw OAuth2Error.noClientSecret
}
let req = OAuth2AuthRequest(url: (clientConfig.tokenURL ?? clientConfig.authorizeURL), method: .GET)
req.params["code"] = code
req.params["grant_type"] = type(of: self).grantType
req.params["redirect_uri"] = redirect
req.params["client_id"] = clientId
req.params["client_secret"] = clientSecret
return req
}