使用refreshToken实现Alamofire RequestInterceptor



我正在尝试处理401未经授权的请求与Alamofire (5.6.1)

我应该使用哪个Alamofire实现?

在第一个login post方法中,我得到了这样的数据:

{
"authToken": "auth12345",
"refreshToken": "refresh6789"
}

之后,对于每个请求到我的API端点(例如baseURL+">/user/API/user-address")
我使用authToken

["Authorization": "Bearer (authToken)", "Accept": "application/json"]

authToken过期时刻我开始收到401代码-这是未经授权的请求。

获取新的authToken我必须用refreshToken发出请求到特定的端点,即
baseURL + /auth/api/refresh-token

通过阅读alamofire文档,我有点困惑哪个实现RequestInterceptor我必须用:

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

它只是修改头(headers.add)与相同的过期accessTokennot给出选项

呼叫特定端点with

也有实现class OAuthAuthenticator: Authenticator

的例子struct OAuthCredential: AuthenticationCredentia也不可见,因为我提供

专用的端点机制刷新authTokenrefreshToken。

如果您可以检查您的令牌是否提前过期,您可以在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).
}

相关内容

  • 没有找到相关文章

最新更新