![](/img/trans.png)
[英]Alamofire 5.0.0-rc.3 RequestInterceptor Adapt method not being called of Alamofire although retry gets called when there is any error in response
[英]Implementation of Alamofire RequestInterceptor with refreshToken
我正在尝试使用 Alamofire (5.6.1) 处理 401 未经授权的请求
我应该使用哪个 Alamofire 实现?
首先登录后方法我得到了那种数据:
{
"authToken": "auth12345",
"refreshToken": "refresh6789"
}
之后对我的 API 端点的每个请求(例如baseURL + “ /user/api/user-address ”)
我正在使用带有authToken的 header
["Authorization": "Bearer \(authToken)", "Accept": "application/json"]
在authToken到期的那一刻,我开始收到 401 代码 - 这是未经授权的请求。
要获得新的authToken ,我必须使用refreshToken向特定端点发出请求,即:
baseURL + /auth/api/refresh-token
通过阅读alamofire 文档,我有点混淆了我必须使用哪个实现RequestInterceptor go:
RequestAdapter, RequestRetrier - 说要实现:
1. func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void)
2. func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void)
但正如我看到的例子:
func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {
var urlRequest = urlRequest
urlRequest.headers.add(.authorization(bearerToken: accessToken))
completion(.success(urlRequest))
}
它只是用相同的过期accessToken修改 header ( headers.add
) 而不是给你选项
使用refreshToken调用特定端点
还有实施示例class OAuthAuthenticator: Authenticator
and
struct OAuthCredential: AuthenticationCredentia
这对我来说也是不可见的
专用端点使用refreshToken刷新authToken的机制。
如果可以提前检查自己的token是否过期,可以在adapt
方法中实现刷新:
func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {
// Check token expiration.
// If expired, call refresh, then call completion.
// If not expired, adapt the request like normal and call completion.
}
如果你不能这样做,只需实现你已经拥有的正常adapt
并在retry
中实现刷新:
func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) {
// If error is 401, refresh the tokens, then call the completion handler to trigger retry.
// Retrying the request should then call adapt with the new token.
// If the error isn't 401 and you don't want to retry, call completion(.doNotRetry).
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.