AuthenticationInterceptor(Alamofire5.2) 重试过程不能正常工作

Posted

技术标签:

【中文标题】AuthenticationInterceptor(Alamofire5.2) 重试过程不能正常工作【英文标题】:AuthenticationInterceptor(Alamofire5.2) retry process doesn't work well 【发布时间】:2020-06-25 14:17:48 【问题描述】:

我对 Alamofire 5.2 中添加的 AuthenticationInterceptor 有疑问。 我正在使用 AuthenticationInterceptor 刷新 oAuth 令牌。 https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#authenticationinterceptor

我正在尝试的代码如下。


struct OAuthCredential: AuthenticationCredential 
    let accessToken: String
    let refreshToken: String
    let userID: String
    let expiration: Date

    // Require refresh if within 5 minutes of expiration
    var requiresRefresh: Bool  Date(timeIntervalSinceNow: 60 * 5) > expiration 



class OAuthAuthenticator: Authenticator 
    func apply(_ credential: OAuthCredential, to urlRequest: inout URLRequest) 
        urlRequest.headers.add(.authorization(bearerToken: credential.accessToken))
    

    func refresh(_ credential: OAuthCredential,
                 for session: Session,
                 completion: @escaping (Result<OAuthCredential, Error>) -> Void) 
        
        // Request to refresh token
        let request = Session.default.request(
            URL(string: "URL for token refresh")!,
            method: .patch,
            parameters: ["refresh_token": credential.refreshToken]
        )
        
        request.responseJSON  response in
            // Get new Credential information
            // ~~~~~~
            completion(.success(newCredential))
        
    

    func didRequest(_ urlRequest: URLRequest,
                    with response: HTTPURLResponse,
                    failDueToAuthenticationError error: Error) -> Bool 
        return response.statusCode == 401
    

    func isRequest(_ urlRequest: URLRequest, authenticatedWith credential: OAuthCredential) -> Bool 
        let bearerToken = HTTPHeader.authorization(bearerToken: credential.accessToken).value
        return urlRequest.headers["Authorization"] == bearerToken
    


// ~~~~~~
let session = Session.default
let urlRequest = try! URLRequest(
    url: URL(string: "https://api.example/docs")!,
    method: .get
)
        
        
session.request(urlRequest, interceptor: interceptor).responseJSON  response in
    // ~~~~~

我不知道是否有时会调用 didRequestisRequest。我在粘贴断点时调试时遇到401错误,但并没有停止在上面的方法。

没有调用这些方法的原因是它们总是会在下面的行中返回。 https://github.com/Alamofire/Alamofire/blob/4f72b95b49c22e445e1866712f719698fa11c30c/Source/AuthenticationInterceptor.swift#L297 我找不到没有经过这条线的案例。

我想知道调用两个方法的情况。

【问题讨论】:

您是否在拦截器中添加了凭据?让拦截器= AuthenticationInterceptor(身份验证器:身份验证器,凭据:凭据,刷新窗口:窗口) 【参考方案1】:

尝试拨打.validate()

    session.request(urlRequest, interceptor: interceptor).validate().responseJSON  response in
        // ~~~~~
    

【讨论】:

以上是关于AuthenticationInterceptor(Alamofire5.2) 重试过程不能正常工作的主要内容,如果未能解决你的问题,请参考以下文章

Java 定义基础拦截器

Java 定义基础拦截器