web-dev-qa-db-ja.com

Alamofireにアクセストークンを渡す方法は?

アクセストークンをAlamofireで渡そうとしていますが、Web上のさまざまな方法で混乱しています。

以下は、使用する必要があるメソッドです。

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

アクセストークンを渡す適切な方法は何ですか?

11
Sandesh Sardar

あなたはこれを試しましたか?それは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)
    }

もう1つの方法は次のとおりです。

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

これは、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            

    }
4
H S Progr

私はこのように見えるを使用しています:-

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

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