如何使用oauth发送https GET请求

时间:2017-04-06 06:04:41

标签: ios json swift oauth get

我使用OAuth构建项目swift,我已经从我的API登录获得了Acces Token,然后我希望从我的访问令牌获取API JSon的数据。那么,如何使用OAuth获取请求http方法与OAuth和我的访问令牌

我有没有OAuth的json parse标准

let url = NSURL(string: "https://conversation.8villages.com/1.0/contents/articles?state=published")
    let request = NSMutableURLRequest(url: url! as URL)
    request.httpMethod = "GET"

    request.addValue("application/json", forHTTPHeaderField: "Authorization")

    let task = URLSession.shared.dataTask(with: request as URLRequest) { data,response,error in

        guard error == nil && data != nil else {
            print("error", error!)
            return
        }

        let httpStatus = response as? HTTPURLResponse

        if httpStatus!.statusCode == 200
        {
            if data?.count != 0
            {
              let responString = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments)
                print(responString)
            }
            else{
                print("No got data from URL")
            }
        }
        else
        {
            print("error httpstatus code is ", httpStatus!.statusCode)
        }
    }

    task.resume()

我使用了Librabry https://github.com/OAuthSwift/OAuthSwift

在那里我得到了像这样的签名请求(Readme.md)

oauthswift.client.get("https://api.linkedin.com/v1/people/~",
 success: { response in
let dataString = response.string
print(dataString)
},
failure: { error in
print(error)
}
)

但我很困惑如何添加我的Acces令牌,消费者密钥和我的消费者秘密来访问我的API JSON

2 个答案:

答案 0 :(得分:0)

如果您有访问令牌,那么您似乎已经使用了您的使用者密钥和使用者密钥,并且您已通过身份验证。您需要在API get call的授权标头中传递承载访问令牌。

答案 1 :(得分:0)

我不熟悉OAuthSwift框架,但我猜错误在以下一行:

request.addValue("application/json", forHTTPHeaderField: "Authorization")

也许应该是:

request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue(tokenType + " " + accessToken, forHTTPHeaderField: "Authorization")

OAuth授权代码授权类型的tokenType始终是字符串Bearer,而accessToken当然是您之前获得的访问令牌。

编辑: 与Microsoft Azure AD比较:

GET /v1.0/me/messages
Host: https://graph.microsoft.com
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUz...