[英]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.