# OAuthClient
**Repository Path**: zb213/OAuthClient
## Basic Information
- **Project Name**: OAuthClient
- **Description**: 将开源的java+gradle实现oauth认证重写为java+maven的练习,以便更深刻地理解gradle、maven和oauth
- **Primary Language**: Java
- **License**: Apache-2.0
- **Default Branch**: main
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 0
- **Created**: 2026-07-02
- **Last Updated**: 2026-07-03
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# OAuth Client - Maven 重构版
> **致谢**:本项目基于 [https://github.com/capitalone/OAuthClient](https://github.com/capitalone/OAuthClient) 重构,将构建工具从 Gradle 迁移为 Maven。
[](https://www.apache.org/licenses/LICENSE-2.0)
**中文版本** | [English](README.md)
# Java Auth Client Library
# 目录
1. [概述](#概述)
1. [获取 OAuth Token](#获取-oauth-token)
2. [维护 OAuth Token 生命周期](#维护-oauth-token-生命周期)
2. [示例用法](#示例用法)
3. [依赖项](#依赖项)
4. [与原项目的差异](#与原项目的差异)
5. [许可证](#许可证)
## 概述
支持 OAuth 认证并提供接口以添加更多认证方法。
从概念上讲,该库分为两部分:
1. 获取 OAuth Token
2. 维护 OAuth Token 生命周期
### 获取 OAuth Token
`OAuthClientCredentials` 是获取 Token 的基础。它包含请求应用的客户端信息,包括:
1. `grantType`(请求的授权类型)
2. `clientId`(您的应用 ID)
3. `clientSecret`(您的应用密钥)
该类还包含其他信息,例如授权服务器的 URL(`authURI`)和用于匹配需要授权的客户端 URI 的正则表达式模式(`clientURIRegex`)。
假设您有两个 URI — 一个是 http://awesomeserver.com/hello ,另一个是 http://coolserver.com/hello 。如果这两个 URI 都需要来自同一服务器的授权,并且可以使用同一组客户端凭据完成该授权,那么您只需要一个 `OAuthClientCredentials` 类实例,但 `clientURIRegex` 中的正则表达式需要能够匹配这两个 URI。然而,如果这两个 URI 需要不同的客户端凭据集或不同的授权服务器(或两者都不同),那么您需要两个独立的实例。
一旦您拥有一个或多个 `OAuthClientCredentials` 类实例,创建一个类型为 `OAuthClientCredentials` 的 `ClientCredentialsProvider` 类实例。该类至少需要一个 `OAuthClientCredentials` 实例,因此需要在构造函数中传入。
`ClientCredentialsProvider` 顾名思义,根据请求提供凭据。当使用 URI 调用 `getClientCredentialsFor` 时,它会遍历其所有 `OAuthClientCredentials` 对象,并对给定的 URI 运行 `clientURIRegex` 匹配。它返回第一个匹配该 URI 的 `OAuthClientCredentials`。
一旦您拥有一个可用的 `ClientCredentialsProvider` 实例,创建一个 `OAuthTokenService` 实例。构造函数需要以下参数:
1. `httpConnectionFactory`(生成 HTTP 连接的工厂)
2. `httpConnectionConfig`(HTTP 连接的配置,包括 sslProtocol,默认为 TLSv1.2)
3. `prefetchPoolSize`(预取池的大小 — 稍后会详细介绍)
4. `oAuthClientCredentialsProvider`(您的 OAuthClientCredentials 提供者实例)
首次请求 Token 时(使用 `obtainTokenFor`),该服务直接返回 `OAuthToken` 对象作为 `Token`。
### 维护 OAuth Token 生命周期
`Token` 对象在首次返回时立即被缓存。当下一次请求到来时,如果 Token 尚未过期,它直接返回缓存的 Token。
然而,如果 Token 在过期前还剩一定时间(由 `prefetchTimeout` 定义),Token 服务会启动一个预取任务,异步更新 Token。在此期间到达的所有请求都使用已缓存且即将过期的 Token。一旦异步任务返回有效的 Token,当前 Token 将被该 Token 替换,然后返回给所有后续请求。
如果请求速度变慢,`OAuthTokenService` 没有机会异步更新 Token,它会阻塞当前请求线程并同步获取 Token(然后将其缓存)。
## 示例用法
在您的 Maven pom.xml 文件中包含以下内容。确保将 $version 替换为您要使用的库版本。
```xml
io.github.zb213
oauth-client-java
$version
```
以下是使用该库的示例客户端应用:
```java
package io.github.zb213.auth.example;
import io.github.zb213.auth.ClientCredentialsProvider;
import io.github.zb213.auth.TokenService;
import io.github.zb213.auth.oauth.factory.HttpConnectionConfig;
import io.github.zb213.auth.oauth.factory.HttpConnectionFactory;
import io.github.zb213.auth.oauth.factory.HttpConnectionFactoryImpl;
import io.github.zb213.auth.oauth.framework.OAuthClientCredentials;
import io.github.zb213.auth.oauth.framework.OAuthClientCredentialsProvider;
import io.github.zb213.auth.oauth.service.ClientSecretException;
import io.github.zb213.auth.oauth.service.ClientSecretService;
import io.github.zb213.auth.oauth.service.OAuthToken;
import io.github.zb213.auth.oauth.service.OAuthTokenService;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.locks.ReentrantLock;
public class ExampleClient {
private final TokenService oAuthTokenService;
public static void main(String[] args) {
ExampleClient client = new ExampleClient();
client.makeRequest();
}
public ExampleClient() {
URI authServerURI = null;
try {
authServerURI = new URI("https://myoauthserver.com/oauth/oauth20/token");
} catch (URISyntaxException e) {
e.printStackTrace();
}
OAuthClientCredentials builtClientCredentials = OAuthClientCredentials.newBuilder()
.clientId("my_client_id")
.clientSecret("my_client_secret")
.clientSecretEncryptionKey(null)
.clientURIRegex(".*")
.grantType("client_credentials")
.authServerURI(authServerURI)
.build();
ClientCredentialsProvider clientCredentialsProvider = new OAuthClientCredentialsProvider(builtClientCredentials);
ClientSecretService clientSecretService = new DummyClientSecretService();
HttpConnectionFactory httpConnectionFactory = new HttpConnectionFactoryImpl(new ReentrantLock());
HttpConnectionConfig httpConnectionConfig = HttpConnectionConfig.newBuilder()
.httpConnectionTimeout(60000)
.httpSocketTimeout(40000)
.maxHttpConnections(20)
.sslProtocol("TLSv1.2")
.build();
oAuthTokenService = new OAuthTokenService(httpConnectionFactory, httpConnectionConfig, 20, 10, clientCredentialsProvider, clientSecretService);
}
public void makeRequest() {
try {
OAuthToken token = (OAuthToken) oAuthTokenService.obtainTokenFor(new URI("https://myoauthserver.com/partners/sparkpost/transmissions"));
System.out.println(token.getValue());
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
}
}
private class DummyClientSecretService implements ClientSecretService {
@Override
public String obtainClientSecret(OAuthClientCredentials clientCredentials) throws ClientSecretException {
if (null == clientCredentials.getClientSecretEncryptionKey()) {
return clientCredentials.getClientSecret();
} else {
return decryptSecret(clientCredentials.getClientSecretEncryptionKey(), clientCredentials.getClientSecret());
}
}
private String decryptSecret(String encryptionKey, String encryptedClientSecret) {
return "abc1";
}
}
}
```
## 依赖项
| 库 | 版本 | 许可证 |
| ---------------------------------------------- | ------- | -------------------- |
| commons-io:commons-io | 2.4 | Apache 2.0 |
| org.apache.httpcomponents:httpclient | 4.5.2 | Apache 2.0 |
| com.fasterxml.jackson.core:jackson-databind | 2.3.4 | Apache 2.0 |
| commons-lang:commons-lang | 2.6 | Apache 2.0 |
| junit:junit | 4.11 | CAPL 1.0, CPL 1.0 |
| org.mockito:mockito-core | 1.10.19 | MIT |
| org.hamcrest:hamcrest-all | 1.3 | BSD 2-clause |
## 与原项目的差异
| 差异项 | 原项目 | 重构版 |
|--------|--------|--------|
| **构建工具** | Gradle | Maven |
| **项目坐标** | `com.capitalone.util:c1-oauth-client-java` | `io.github.zb213:oauth-client-java` |
| **Java 版本** | 1.7 | 1.8 |
| **依赖管理** | `build.gradle` | `pom.xml` |
## 许可证
Apache License 2.0
参见 [LICENSE](LICENSE) 文件获取完整许可证文本。