嗨我在执行身份验证过程时遇到了Instagram的问题。 它在几周前工作正常,代码中没有任何变化。
现在面临的问题是,在Instagram的登录过程之后,safari会显示错误" Bad request 400"而且仅此而已。
答案 0 :(得分:3)
最近我遇到了与Instagram api相同的问题。一切都很好,突然有400个错误的请求 - 你必须提供一个client_id。
我调试了OAuth 2.0流程,经过广泛研究后发现我应该设置一个
内容类型:应用程序/ X WWW的窗体-urlencoded 强>
请求中的标头。因此,如果其他人遇到此问题,请确保在检索访问令牌的请求中设置了标头。
答案 1 :(得分:1)
由于重定向uri,我使用了WKWEbView
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
//print(webView.url?.absoluteString)
decisionHandler(.allow)
let searchString = "https://example.com"//your redirect uri
if (webView.url?.absoluteString.starts(with: searchString))! {
let code = extractCode(webView.url!.absoluteString)
if code != nil{
print("*****found")
print("code: \(code)")
self.loginWithInstagram(code!)
}
}
}
func loginWithInstagram(_ code: String) {
let headers = [
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "*/*",
"Cache-Control": "no-cache",
"Host": "api.instagram.com",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "237",
"Connection": "keep-alive",
"cache-control": "no-cache"
]
let postData = NSMutableData(data: "client_id=xxx".data(using: String.Encoding.utf8)!)
postData.append("&code=".data(using: String.Encoding.utf8)!)
postData.append(code.data(using: String.Encoding.utf8)!)
postData.append("&redirect_uri=https://example.com".data(using: String.Encoding.utf8)!)
postData.append("&grant_type=authorization_code".data(using: String.Encoding.utf8)!)
postData.append("&client_secret=xxx".data(using: String.Encoding.utf8)!)
let request = NSMutableURLRequest(url: NSURL(string: "https://api.instagram.com/oauth/access_token")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
guard let unwrappedData = data else { return }
do {
let str = try JSONSerialization.jsonObject(with: unwrappedData, options: .allowFragments)
print(str)
} catch {
print("json error: \(error)")
}
if (error != nil) {
//print(error)
} else {
let httpResponse = response as? HTTPURLResponse
//print(httpResponse)
}
})
dataTask.resume()
}
}
//适用于我的应用
答案 2 :(得分:0)
您看到的问题与回调网址有关。 Instagram似乎不再接受自定义方案。你的回调需要是http或https(它不能,例如customapp://)。