How to pass access token in ios with alamofire

alamofire refresh token
alamofire requestretrier refresh token
alamofire 4 authorization header
alamofire 5 request adapter
bearer token authentication swift
alamofire swiftui
alamofire authentication
alamofire interceptor

I get access token from API at login But I don't know how to pass token through all interface that must contain this token to retrieve data from API based on user Token.

Here View Controller for login

@IBAction func login(_ sender: UIButton) {
        //getting the username and password
        let parameters: Parameters=[
        var token = String()// global variable
        let headers = [
            "Authorization" : String(format: "Bearer: @%", token)
        Alamofire.request(URL_USER_LOGIN, method: .post, parameters: parameters, headers: headers).responseJSON
                response in

                //getting the json value from the server
                        if let result = response.result.value {
                            let jsonData = result as! NSDictionary

                           // if there is no error
                            if((!(jsonData.value(forKey: "error") != nil) )){
                                // if there is a token
                                token = (jsonData.object(forKey: "access_token") as! String?)!
                                       //switching the screen
                      let Home_AdminViewController = self.storyboard?.instantiateViewController(withIdentifier: "TabBarViewController") as! TabBarViewController
                    self.navigationController?.pushViewController(Home_AdminViewController, animated: true)
                          self.dismiss(animated: false, completion: nil)
                            else {
                                //error message in case of invalid credential
                                self.LabelMessage.text = "Invalid username or password"


You can create a simple struct with static variables like:

struct Credentials {
    static var token: String?
    static var refreshToken: String?

This, you can call: Credentials.token or Credentials.refreshToken

Or simply, in an empty swift file, add this variables without any class or struct:

var token: String?
var refreshToken: String?

In this case, you can access this directly token in any file

iOS: OAuth handler in Swift using Alamofire + , And RequestRetrier gives you the opportunity to handle a request that encountered an Error to be retried, for example, for refresh session token� Home · iOS & Swift Tutorials Alamofire Tutorial: Getting Started. Take your first steps into Alamofire, the de facto networking library on iOS powering thousands of apps, by using the Imagga APIs to upload and analyze user photos.

You can try below code

let auth = "your token"
let authData = String.Encoding.utf8)!
let base64EncodedCredential = authData.base64EncodedString()
let authString = "Basic \(base64EncodedCredential)"
let authorization = ["Authorization" : authString]

Make upper code constant as global in some file

Alamofire.request(url, method: .get, parameters: para, encoding: URLEncoding.default, headers: authorization).responseSwiftyJSON { (result) in
      print("response:=",result.value ?? "nil")

Authentication with signed requests in Alamofire, /// Set the Authorization header value using the access token. urlRequest. setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization") Step 10: Select the Token a. Tap the back button on your phone to select the MobilePASS+ app. b. At the MobilePASS+ screen, tap the token name to generate a token passcode. NOTE: the MobilePASS+ app allows multiple software tokens to be installed, however, the UTC policy is one token per user. You may tap the Gear Icon to delete

You can check out the docs in Alamofire about RequestAdatper, I think this is what you want.

class AccessTokenAdapter: RequestAdapter {
    private let accessToken: String

    init(accessToken: String) {
        self.accessToken = accessToken

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

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

        return urlRequest
let sessionManager = SessionManager()
sessionManager.adapter = AccessTokenAdapter(accessToken: "1234")


Authentication with signed requests in Alamofire 5, Alamofire is a popular framework and makes it easy to set up networking you can tell that Alamofire is a popular framework to use for iOS and Mac projects The storage containing your access token, preferable a Keychain� how is it possible to send a POST request with a simple string in the HTTP body with Alamofire in my iOS app? As default Alamofire needs parameters for a request: Alamofire . request (.

thanks all! I got the answer using Keychainwrapper library

first I save the access token in login request then I can use anywhere.

Getting an OAuth 2.0 Token with Alamofire, For example, if you wanted to let an iOS app have some access to your If we got a token, call the completion handler without passing an error� I'm making some weather app. and i want to show weather info on widget too So i tried to import Alamofire in Widget's ViewController but it couldn't find module I also check tutorial from other blog or website, but in my project i cannot find Alamofire in `Linked Frameworks and Libraries like this

Alamofire Authentication: Basic & HTTP Headers, tl;dr: Alamofire can be used to do Basic or HTTP header auth. practice using a REST API so we're going to pretend their iOS SDK doesn't exist. “spots”; Add headers to our Alamofire request so our GET request doesn't fail� I am building both an iOS client and a django backend service. The connection made between the systems is OAUTH2, implemented by the django-oauth2-toolkit. Although the following command done in curl works (returns an access token):

Authorization header not sent for GET method in swift 3 � Issue , I am sending bearer token in header which is working for post method. The code Alamofire.request(url, method: .get, headers: headers). Exchange the code for an access token; Use the access token to access the API; Step 3 is the extra step I referred to at the start of this post. The user doesn’t see it happen so we don’t always think of it as part of the OAuth 2.0 flow but as coders we need to implement it. Step 1: Send Users to GitHub

OAuthSwift/OAuthSwiftAlamofire: Utility method to sign , Refresh token. The OAuth2 interceptor will also automatically refresh the access token, using the Alamofire RequestRetrier mechanism. Installation. iOS alamofire ObjectMapper AlamofireObjectMapper APIRouter Report Bài viết này dành cho những người mới bắt đầu làm quen với iOS như mình, và với những đàn anh đi trước thì mình rất mong nhận được ý kiến đóng góp anh em cùng nâng cao kiến thức

  • How to call swift file in view controller ? to access token
  • If you use the struct, call it Credentials.token, if not, call it directly token in any view controller or other Swift file @Nora