【问题标题】:Your credentials do not allow access to this resource Twitter API Error您的凭据不允许访问此资源 Twitter API 错误
【发布时间】:2019-08-17 19:08:21
【问题描述】:

我正在开发 twitter api,一些 api 正在获得响应。但是statuses/home_timeline.json api 和其他 api 没有得到响应。

得到错误:

{"errors":[{"code":220,"message":"Your credentials do not allow access to this resource."}]}

我已成功获取访问令牌并将该访问令牌用于statuses/home_timeline.json 和其他一些 api。但这些都超出了错误。我已经用我的帐户登录了。

我找到了很多网址,但我没有从这些网址中得到答案。

我的Accesstoken代码是:

//Get twitter access token
func getAccessToken() {

    //RFC encoding of ConsumerKey and ConsumerSecretKey
    let encodedConsumerKeyString:String = "f4k***********0".addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)!
    let encodedConsumerSecretKeyString:String = "OD**************ln".addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)!
    print(encodedConsumerKeyString)
    print(encodedConsumerSecretKeyString)
    //Combine both encodedConsumerKeyString & encodedConsumerSecretKeyString with " : "
    let combinedString = encodedConsumerKeyString+":"+encodedConsumerSecretKeyString
    print(combinedString)
    //Base64 encoding
    let data = combinedString.data(using: .utf8)
    let encodingString = "Basic "+(data?.base64EncodedString())!
    print(encodingString)
    //Create URL request
    var request = URLRequest(url: URL(string: "https://api.twitter.com/oauth2/token")!)  //oauth/access_token   oauth2/token
    request.httpMethod = "POST"
    request.setValue(encodingString, forHTTPHeaderField: "Authorization")
    request.setValue("application/x-www-form-urlencoded;charset=UTF-8", forHTTPHeaderField: "Content-Type")
    let bodyData = "grant_type=client_credentials".data(using: .utf8)!
    request.setValue("\(bodyData.count)", forHTTPHeaderField: "Content-Length")
    request.httpBody = bodyData

    let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { // check for fundamental networking error
        print("error=\(String(describing: error))")
        return
        }

//            let responseString = String(data: data, encoding: .utf8)
//            let dictionary = data
//            print("dictionary = \(dictionary)")
//            print("responseString = \(String(describing: responseString!))")

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(String(describing: response))")
        }

        do {
            let response = try JSONSerialization.jsonObject(with: data, options: []) as! Dictionary<String, Any>
            print("Access Token response : \(response)")
//                print(response["access_token"]!)
//                self.accessToken = response["access_token"] as! String
            if let token = response["access_token"] {
                self.accessToken = token as! String
            }

        } catch let error as NSError {
            print(error)
        }
    }

    task.resume()
}

Twitter 签名代码:

//Twitter signin
@IBAction func onClickTwitterSignin(_ sender: UIButton) {

    //Login and get session
    TWTRTwitter.sharedInstance().logIn { (session, error) in

        if (session != nil) {
            //Read data
            let name = session?.userName ?? ""
            print(name)
            print(session?.userID  ?? "")
            print(session?.authToken  ?? "")
            print(session?.authTokenSecret  ?? "")

 //                self.loadFollowers(userid: session?.userID ?? "")

 //                let userid = session?.userID ?? ""
 //                let screenName = session?.userName ?? ""
 //                if userid != "" && screenName != "" {



             self.getStatusesUserTimeline(accessToken:self.accessToken)


 //                }

            //Get user email id
            let client = TWTRAPIClient.withCurrentUser()
            client.requestEmail { email, error in
                if (email != nil) {
                    let recivedEmailID = email ?? ""
                    print(recivedEmailID)
                } else {
                    print("error--: \(String(describing: error?.localizedDescription))");
                }
            }
            //Get user profile image url's and screen name
            let twitterClient = TWTRAPIClient(userID: session?.userID)
            twitterClient.loadUser(withID: session?.userID ?? "") { (user, error) in
                print(user?.profileImageURL ?? "")
                print(user?.profileImageLargeURL ?? "")
                print(user?.screenName ?? "")
            }



            let storyboard = self.storyboard?.instantiateViewController(withIdentifier: "SVC") as! SecondViewController
            self.navigationController?.pushViewController(storyboard, animated: true)
        } else {
            print("error: \(String(describing: error?.localizedDescription))");
        }
    }

}

Get twitter statuses/home_timeline.json : (我在登录成功后调用这个函数)

func getStatusesUserTimeline(accessToken:String) {

    let userId = "10************56"
    let twitterClient = TWTRAPIClient(userID: userId)
    twitterClient.loadUser(withID: userId) { (user, error) in
        print(userId)
        print(user ?? "Empty user")
        if user != nil {


            //Get users timeline tweets
            var request = URLRequest(url: URL(string: "https://api.twitter.com/1.1/statuses/home_timeline.json?")!)                


            request.httpMethod = "GET"
            request.setValue("Bearer "+accessToken, forHTTPHeaderField: "Authorization")
            print(request)

            let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { // check for fundamental networking error
                print("error=\(String(describing: error))")
                return
                }


                if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
                    print("statusCode should be 200, but is \(httpStatus.statusCode)")
                    print("response = \(String(describing: response))")
                }

                do {
                    let response = try JSONSerialization.jsonObject(with: data, options: []) as! Dictionary<String,Any>
                    print(response)
 //                        print((response["statuses"] as! Array<Any>).count)

                } catch let error as NSError {
                    print(error)
                }
            }

            task.resume()

        } else {
            print(error?.localizedDescription as Any)
        }
    }

}

【问题讨论】:

  • 您正在尝试使用 Bearer 令牌(仅限应用程序身份验证),但这不起作用。您需要时间线端点的用户身份验证。
  • @Andy Piper,谢谢,请您简要解释一下 Bearer 令牌(仅限应用程序身份验证)和我获取 home_timeline.json 数据所需的令牌。我研究了很多网址,但我不明白。
  • 您需要用户访问令牌。这意味着使用“使用 Twitter 登录”流程来执行用户身份验证。在此页面上阅读有关应用程序用户身份验证的部分developer.twitter.com/en/docs/basics/authentication/overview/…

标签: ios swift twitter oauth twitter-oauth


【解决方案1】:

检查权限如下截图。转到开发者帐户 -> 仪表板 -> 选择您的应用 -> 权限。

您是在使用仅限应用的身份验证,还是使用只有只读权限的应用?

请确保您的应用具有读写权限或读取、写入和直接消息权限

【讨论】:

  • 谢谢。我已经启用了读取、写入和直接消息选项。但是没用。
猜你喜欢
  • 2014-06-05
  • 2016-11-11
  • 2014-08-19
  • 2018-03-02
  • 2016-01-18
  • 2014-06-14
  • 2019-12-04
  • 1970-01-01
  • 2017-08-06
相关资源
最近更新 更多