如何将访问令牌传递给 Alamofire? [英] How to pass access token to Alamofire?

查看:34
本文介绍了如何将访问令牌传递给 Alamofire?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Alamofire 中传递访问令牌,但在网络上的各种方法中感到困惑.

I am trying to pass access token in Alamofire but getting confuse in various methods around web.

以下是我们需要使用的方法.

Below are methods which we need to use.

let todosEndpoint: String = "https:url......."

let headers = [
            "Authorization": "Bearer (token!)",
            "Content-Type": "application/X-Access-Token"
        ]
        let Auth_header    = [ "Authorization" : tokenString! ]

        Alamofire.request(todosEndpoint, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: Auth_header)
            .responseJSON { response in
                print("response.request (response.request)")  // original URL request
                print("response.response (response.response)") // HTTP URL response
                print("response.data (response.data)")     // server data
                print("response.result (response.result)")

                print("response (response)")

        }

    }

let aManager = SessionManager()
        aManager.session.configuration.httpAdditionalHeaders = [
            "Authorization": "Bearer tokenString"]

let headerss = [
            "Authorization": tokenString]

let aManager = SessionManager()
            aManager.session.configuration.httpAdditionalHeaders = [
                "Authorization": "Basic tokenString"]

传递访问令牌的正确方法是什么?

What is proper way to pass access token?

推荐答案

你试过了吗,它可以在 Alamofire 文档中找到:

Did you tried this, it's available in Alamofire documentation:

let headers: HTTPHeaders = [
    "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
    "Accept": "application/json"
]

Alamofire.request("https://httpbin.org/headers", headers: headers).responseJSON { response in
    debugPrint(response)
}

另一个例子是:

let user = "user"
let password = "password"

var headers: HTTPHeaders = [:]

if let authorizationHeader = Request.authorizationHeader(user: user, password: password) {
    headers[authorizationHeader.key] = authorizationHeader.value
}

Alamofire.request("https://httpbin.org/basic-auth/user/password", headers: headers)
    .responseJSON { response in
        debugPrint(response)
    }

另一种方法是:

let user = "user"
let password = "password"

let credential = URLCredential(user: user, password: password, persistence: .forSession)

Alamofire.request("https://httpbin.org/basic-auth/(user)/(password)")
    .authenticate(usingCredential: credential)
    .responseJSON { response in
        debugPrint(response)
    }

这篇关于如何将访问令牌传递给 Alamofire?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆