目录

OkHttp源码学习之Authenticator

OkHttp 中,Authenticator 是一个用于处理 HTTP 认证(Authentication)的接口,主要用于在服务端要求身份验证时自动提供凭据(如用户名和密码)。

Authenticator 的作用

  1. 处理 HTTP 401(Unauthorized)和 407(Proxy Authentication Required)状态码

    当服务器或代理返回这些状态码时,Authenticator 会被调用以提供认证信息。

  2. 自动重试请求
    OkHttp 使用 Authenticator 生成包含认证头的请求,并自动重试。这简化了开发流程,无需手动处理这些情况。

  3. 支持多种认证方式

    通过自定义实现,可以支持 BasicBearer 或其他定制的认证方式。

Authenticator 的实现

Authenticator 是一个函数式接口,定义了以下方法:

less 复制代码
java
复制代码
public interface Authenticator {
    Request authenticate(@Nullable Route route, Response response) throws IOException;
}

参数说明

  • route:提供网络请求的路由信息(如目标主机和端口)。
  • response:包含服务端的响应信息,通常包含 WWW-AuthenticateProxy-Authenticate 头,用于指示所需的认证方式。

返回值

  • 返回一个新的 Request 对象,其中包含了认证头(AuthorizationProxy-Authorization)。
  • 返回 null 表示放弃认证,OkHttp 不会重试请求。

默认 Authenticator

  • Authenticator.NONE :表示不处理认证,返回 null

常见场景与实现

1. Basic Authentication

kotlin 复制代码
val basicAuthenticator = Authenticator { _, response ->
    val credentials = Credentials.basic("username", "password")
    response.request.newBuilder()
        .header("Authorization", credentials)
        .build()
}

val client = OkHttpClient.Builder()
    .authenticator(basicAuthenticator)
    .build()

2. Token Authentication

当需要在请求中添加 Bearer Token 或自定义的认证信息时:

kotlin 复制代码
val tokenAuthenticator = Authenticator { _, response ->
    val token = "your-token-here"  // Replace with logic to retrieve token
    response.request.newBuilder()
        .header("Authorization", "Bearer $token")
        .build()
}

val client = OkHttpClient.Builder()
    .authenticator(tokenAuthenticator)
    .build()

3. Proxy Authentication

针对代理服务器的认证:

kotlin 复制代码
val proxyAuthenticator = Authenticator { _, response ->
    val credentials = Credentials.basic("proxyUser", "proxyPassword")
    response.request.newBuilder()
        .header("Proxy-Authorization", credentials)
        .build()
}

val client = OkHttpClient.Builder()
    .proxyAuthenticator(proxyAuthenticator)
    .build()

重要注意事项

  1. 避免无限循环

    • 如果认证失败,服务端可能继续返回 401407 状态码,这个时候我们需要添加退避策略或者控制重试次数。
    • 确保在 Authenticator 中检查重试次数或响应的请求历史,以避免无限重试。
    kotlin 复制代码
    val limitedRetryAuthenticator = Authenticator { _, response ->
        if (response.request.header("Authorization") != null) {
            // 防止无限重试
            null
        } else {
            val credentials = Credentials.basic("username", "password")
            response.request.newBuilder()
                .header("Authorization", credentials)
                .build()
        }
    }
  2. 线程安全性

    • 如果 Authenticator 需要访问共享资源(如刷新令牌),确保实现是线程安全的。
  3. 避免将敏感信息硬编码

    • 使用安全存储(如 Android 的 Keystore)来存储凭据。
本文是转载文章,点击查看原文
如有侵权,请联系 xyy@jishuzhan.net 删除
相关推荐
兰亭序咖啡31 分钟前
学透Spring Boot — 018. 优雅支持多种响应格式
java·spring boot·后端
小雨凉如水35 分钟前
docker 常用命令
java·docker·eureka
高山流水&上善1 小时前
医药档案区块链系统
java·springboot
南汐以墨1 小时前
探秘JVM内部
java·jvm
Craaaayon1 小时前
Java八股文-List集合
java·开发语言·数据结构·list
沅霖1 小时前
Android: Handler 的用法详解
android
鸿蒙布道师2 小时前
鸿蒙NEXT开发数值工具类(TS)
android·ios·华为·harmonyos·arkts·鸿蒙系统·huawei
信徒_2 小时前
Spring 怎么解决循环依赖问题?
java·后端·spring
2301_794461572 小时前
多线程编程中的锁策略
java·开发语言
老华带你飞2 小时前
木里风景文化|基于Java+vue的木里风景文化管理平台的设计与实现(源码+数据库+文档)
java·数据库·vue.js·毕业设计·论文·风景·木里风景文化管理平台