Twitter仅应用程序身份验证始终返回401 [英] Twitter Application-only authentication always return 401
问题描述
我正在尝试仅使用App auth进行身份验证,并且成功获得了承载令牌,但是当我尝试调用REST API时,总是会收到401错误,这是我的代码:
I am trying to authenticate using App only auth and I successfully get the bearer token but when I try to make calls to the REST APIs, I always get an 401 error, here is my code:
private var accessToken: String?
private let consumerKey = "*********"
private let consumerSecret = "*********"
private let baseUrlString = "https://api.twitter.com/1.1/"
private let pageSize = 20
private func authenticate(completionBlock: Void -> ()) {
if accessToken != nil {
completionBlock()
}
let credentials = "\(consumerKey):\(consumerSecret)"
let headers = ["Authorization": "Basic \(credentials.getBase64())"]
let params: [String : AnyObject] = ["grant_type": "client_credentials"]
Alamofire.request(.POST, "https://api.twitter.com/oauth2/token", headers: headers, parameters: params)
.responseJSON { response in
if let JSON = response.result.value {
self.accessToken = JSON.objectForKey("access_token") as? String
completionBlock()
}
}
}
func getTimelineForScreenName(screenName: String) {
authenticate {
guard let token = self.accessToken else {
// TODO: Show authentication error
return
}
let headers = ["Authorization": "Bearer \(token.getBase64())"]
let params: [String : AnyObject] = [
"screen_name" : screenName,
"count": self.pageSize
]
Alamofire.request(.GET, self.baseUrlString + "statuses/user_timeline.json", headers: headers, parameters: params)
.responseJSON { response in
print(response.response)
if let JSON = response.result.value {
print(JSON)
}
}
}
}
...
private extension String {
func getBase64() -> String {
let credentialData = self.dataUsingEncoding(NSUTF8StringEncoding)!
return credentialData.base64EncodedStringWithOptions([])
}
}
我尝试生成新密钥,但什么也没做,也尝试了iOS 9中发现的此错误中的建议,即不让 Authorization
标头通过重定向传递,但此请求未使用任何重定向。
I have tried generating new keys but nothing, also tried what's suggested in this bug found in iOS 9 not letting the Authorization
header get passed on redirects but this request is not using any redirects.
任何想法都将不胜感激。
Any ideas would be greatly appreciated.
推荐答案
经过几个小时的调查,我发现fluke认为不应将带有Bearer Token的标头编码为base64,因此标题应该看起来像这样:
let headers = [ Authorization: Bearer \(token)]
。
After a few hours of investigation I found by fluke that the header with the Bearer Token shouldn't be encoded to base64, so the header should look something like this:
let headers = ["Authorization": "Bearer \(token)"]
.
我希望这对尝试类似操作的人有所帮助,因为文档表示您必须使用base64编码的令牌。
I hope this helps anyone trying something similar because the documentation says you have to use a base64 encoded token.
步骤3:使用承载令牌对API请求进行身份验证< br>
承载令牌可用于向支持仅应用程序身份验证的API端点发出请求。要使用该承载令牌,请构造一个普通的HTTPS请求,并包括一个Authorization标头,其值应为Bearer<步骤2中的base64承载令牌值>
。不需要签名。
这篇关于Twitter仅应用程序身份验证始终返回401的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!