web-dev-qa-db-fra.com

Comment passer le jeton d'accès à Alamofire?

J'essaie de transmettre le jeton d'accès dans Alamofire, mais je ne comprends pas comment utiliser différentes méthodes Web.

Vous trouverez ci-dessous des méthodes que nous devons utiliser.

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

Quelle est la bonne façon de transmettre le jeton d'accès?

7
sss

Avez-vous essayé ceci, il est disponible dans la documentation d'Alamofire:

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

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

Un autre exemple est:

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

Une autre façon est:

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)
    }
8
Ankit Thakur

Cela peut être fait en utilisant Alamofire de la manière suivante:

    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            

    }
3
H S Progr

J'utilise ressembler à ceci: - 

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 ]
1
Mitul Marsoniya

Si vous utilisez Alamofire 4.0 ou une version supérieure, vous pouvez utiliser le protocole RequestAdapter pour intercepter la demande et injecter le jeton JWT. Cette solution est parfaite si vous faites beaucoup de demandes et devez utiliser JWT dans chacune d’elles.

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

Quelque part dans la classe, vous initialisez la SessionManager comme ceci:

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

Et vous l'utilisez quand vous voulez:

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

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