如何将访问令牌传递给Alamofire?

时间:2016-11-25 06:38:24

标签: ios swift3 alamofire ios10

我正在尝试在Alamofire中传递访问令牌,但却在网络上的各种方法中混淆。

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

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)")

        }

    }

OR

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

OR

let headerss = [
            "Authorization": tokenString]

OR

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

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

4 个答案:

答案 0 :(得分:10)

你有没有试过这个,它可以在Alamofire文档中找到:

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)
    }

答案 1 :(得分:3)

可以通过以下方式使用Alamofire来完成:

    let url: String = "https:url......."
    var request = URLRequest(url:  NSURL(string: url)! as URL)

    // Your request method type Get or post etc according to your requirement
    request.httpMethod = "POST"

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

    // Your required parameter in case of Post request
    let parameters: [String: Any] = ["paramter1": "vaue1"]

    request.httpBody = try! JSONSerialization.data(withJSONObject: parameters )

    Alamofire.request(request).responseJSON { (responseObject) -> Void in

      // Your required functionality here            

    }

答案 2 :(得分:1)

我使用的样子如下: -

let username = "Tuser"
let password = "Tpassword"
let credentialData = "\(username):\(password)".data(using: String.Encoding.utf8)!
let base64Credentials = credentialData.base64EncodedString(options: [])
let headers = ["Authorization": "Basic \(base64Credentials)"]

OR

let headers    = [ "Authorization" : token ]

答案 3 :(得分:1)

如果您使用的是Alamofire 4.0或更高版本,则可以使用RequestAdapter协议来拦截请求并注入JWT令牌。如果您提出许多请求并且必须在每个请求中使用JWT,则此解决方案是完美的。

class AccessTokenAdapter: RequestAdapter {
    private let accessToken: String
    private let prefix: String

    public init(accessToken: String, prefix: String) {
        self.accessToken = accessToken
        self.prefix = prefix
    }

    public func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
        var urlRequest = urlRequest

        if let urlString = urlRequest.url?.absoluteString, urlString.hasPrefix(prefix) {
            urlRequest.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization")
        }

        return urlRequest
    }
}

在类中的某个地方,您可以像这样初始化SessionManager

var sessionManager = SessionManager()
sessionManager.adapter = AccessTokenAdapter(accessToken: token, prefix: "https://protected.api.com")

您可以在需要的时候使用它:

sessionManager.request(MyRouter.getCustomData()).responseArray { (response: DataResponse<[CustomData]>) in

        if response.result.isSuccess {
            self.array = response.result.value ?? []
        } else {
            print(response.debugDescription)
        }
    }