简体   繁体   English

alamofire在SessionManager中更新JWT标头

[英]alamofire updating JWT header in SessionManager

I have the following source code. 我有以下源代码。 I have an AlamoFire SessionManager and a ViewController that uses that SessionManager to make a HTTP request. 我有一个AlamoFire SessionManager和一个使用该SessionManager发出HTTP请求的ViewController。

var Almgr : Alamofire.SessionManager = {
    // Create the server trust policies
    let serverTrustPolicies: [String: ServerTrustPolicy] = [
        "localhost": .disableEvaluation
    ]
    // Create custom manager
    let configuration = URLSessionConfiguration.default

    UserDefaults.standard.synchronize()
    var jwt = UserDefaults.standard.string(forKey: conf.JWT_KEY)

    var headers : HTTPHeaders = Alamofire.SessionManager.defaultHTTPHeaders

    let extraHeaders : HTTPHeaders = [
        "Authorization": "Bearer "+(jwt ?? ""),
        "Accept": "application/json"
    ]

    extraHeaders.forEach({ (k, v) in
        headers[k] = v
    })

    configuration.httpAdditionalHeaders = headers
    let man = Alamofire.SessionManager(
        configuration: configuration,
        serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
    )
    return man
}()

From the above code, you can see that, I am reading UserDefaults.standard.string for getting the value of the JWT token and send it in every HTTP request that I make. 从上面的代码中,您可以看到,我正在读取UserDefaults.standard.string以获取JWT令牌的值,并在我发出的每个HTTP请求中将其发送。

The way I consume this Almgr is straight-forward, like, from a viewcontroller, 我使用这种Almgr的方式很简单,就像从视图控制器中一样,

Almgr.request("my-url", method: .get).validate().responseJSON { response in

The problem however is, the Almgr seem to be initialised only once and even if I change the JWT token by setting it to a different value, via, UserDefaults.standard.set(jwt, forKey: conf.JWT_KEY) in the UserDefaults, its value is not fetched. 但是问题是,Almgr似乎只初始化一次,即使我通过通过UserDefaults.standard.set(jwt, forKey: conf.JWT_KEY)将其设置为其他值来更改JWT令牌,值未获取。

In a view controller, I have the following code: 在视图控制器中,我有以下代码:

print("Getting JWT in MyViewController", UserDefaults.standard.string(forKey: conf.JWT_KEY))
Almgr.request("my-url", method: .get).validate().responseJSON { response in

The print statement prints a different (correct) value for the JWT token than the Almgr which uses the old JWT that was there when the application was launched. 与使用启动应用程序时使用的旧JWT的Almgr相比,print语句为JWT令牌打印的值(正确)不同。

Now my question is, how can I make the Almgr always lazily evaluate the correct JWT value, always, when it is called. 现在我的问题是,如何使Almgr总是在调用时总是懒惰地评估正确的JWT值。

I am using Alamofire 4.5 and Swift 4.0 if matters. 如果有问题,我正在使用Alamofire 4.5和Swift 4.0。

The solution is to use Request Adapters. 解决方案是使用请求适配器。

Relevant source code: 相关源代码:

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("https://httpbin.org") {
            urlRequest.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization")
        }

        return urlRequest
    }
}


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

sessionManager.request("https://httpbin.org/get")

Documentation link: https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#adapting-and-retrying-requests 文档链接: https : //github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#adapting-and-retrying-requests

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 Alamofire 4 SessionManager? - How to use Alamofire 4 SessionManager? 在Alamofire 4.0中初始化SessionManager - Initializing a SessionManager in Alamofire 4.0 在Swift 3的Alamofire 4中使用SessionManager下载音频文件 - Download a Audio file using SessionManager in Alamofire 4 in Swift 3 模块“Alamofire”没有名为“SessionManager”的成员 - Module 'Alamofire' has no member named 'SessionManager' Alamofire 4.7 中的自定义 SessionManager 立即取消 - Custom SessionManager in Alamofire 4.7 cancels immediately 如何覆盖Alamofire SessionManager以修改响应以添加标头? - How to override Alamofire SessionManager to modify response in order to add headers? Alamofire 4.9.1 sessionManager.delegate.sessionDidReceiveChallenge 未在 iOS 15 中分配 - Alamofire 4.9.1 sessionManager.delegate.sessionDidReceiveChallenge is not getting assigned in iOS 15 为什么我不能在Alamofire 4.0中使用SessionManager发出请求? - Why can't I make a request with SessionManager in Alamofire 4.0? 在类中一次声明Alamofire.SessionManager以便在类内的各种实用程序函数中使用它 - Declaring Alamofire.SessionManager once in the class for using it in various utility functions inside the class 为什么我无法在Alamofire 4.0中使用SessionManager初始化或发出请求? (更新) - Why can't I initialize or make a request with SessionManager in Alamofire 4.0? (UPDATED)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM