Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass access token to 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)")

        }

    }

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

What is proper way to pass access token?

like image 209
New iOS Dev Avatar asked Nov 25 '16 06:11

New iOS Dev


2 Answers

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

Another example is:

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

One more way is:

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)
    }
like image 105
Ankit Thakur Avatar answered Sep 28 '22 03:09

Ankit Thakur


If you are using Alamofire 4.0 or greater, you can use RequestAdapter protocol to intercept the request and inject the JWT token. This solution is perfect if you make many requests and have to use JWT in each of them.

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

Somewhere in the class you initialize the SessionManager like this:

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

And you use it whenever you want to:

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

        if response.result.isSuccess {
            self.array = response.result.value ?? []
        } else {
            print(response.debugDescription)
        }
    }
like image 25
Mariusz Wiazowski Avatar answered Sep 28 '22 03:09

Mariusz Wiazowski