Swift:未设置请求授权标头

问题描述 投票:2回答:2

我有一个sylius API的请求端点当我用application/json设置内容类型标头时,Authorization标头用精确值Bearer SampleToken通过postman它对预期的响应做出很好的响应但是当我尝试通过URLRequest设置请求授权头时它给出了我的回应

{
    error = "access_denied";
    "error_description" = "OAuth2 authentication required";
}

当我通过查尔斯监控请求时,我注意到Authorization标头被剥离了。我已经尝试了很多种方法来设置授权标题,但没有运气。

func getTotalProducts(page:String){
    let urlPath="https://demo.sylius.com/api/v2/products"
    var request = URLRequest(url:  NSURL(string: urlPath)! as URL)
    request.httpMethod = "GET"

    request.setValue("Bearer SampleToken", forHTTPHeaderField: "Authorization")
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")

    Alamofire.request(request)
        .responseJSON { response in
            switch(response.result){
            case .success(let value):
                print(value)
                break
            case .failure(let error):
                print("something went wrong \(error.localizedDescription)")
            }
        }.session.finishTasksAndInvalidate()
}

原邮递员要求:

enter image description here

ios swift alamofire sylius
2个回答
0
投票

试着改变

request.setValue("Bearer SampleToken", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

    request.allHTTPHeaderFields = [
       "Authorization": "Bearer SampleToken",
       "Content-Type": "application/json"
    ]

0
投票

您的授权令牌应该是user:password的base64编码字符串

request.setValue("Bearer base64EncodedString", forHTTPHeaderField: "Authorization")

© www.soinside.com 2019 - 2024. All rights reserved.