fenghuo/packages/oidc-provider/examples/auto-keypair.md

91 lines
3.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# OIDC Provider - 自动生成密钥对示例
现在OIDC Provider支持为RSA和ECDSA算法自动生成密钥对无需手动提供。
## 基本用法
### 使用RSA算法自动生成密钥对
```typescript
import { OIDCProvider } from '@your-package/oidc-provider';
// 直接使用构造函数创建Provider实例
const provider = new OIDCProvider({
issuer: 'https://auth.example.com',
signingAlgorithm: 'RS256', // 指定算法,密钥对将在首次使用时自动生成
storage: storageAdapter,
findUser: async (userId) => { /* 查找用户逻辑 */ },
findClient: async (clientId) => { /* 查找客户端逻辑 */ },
authConfig: {
passwordValidator: async (username, password) => {
// 验证用户名密码返回用户ID或null
}
}
});
```
### 使用ECDSA算法自动生成密钥对
```typescript
const provider = new OIDCProvider({
issuer: 'https://auth.example.com',
signingAlgorithm: 'ES256', // ECDSA算法密钥对将在首次使用时自动生成
storage: storageAdapter,
findUser: async (userId) => { /* 查找用户逻辑 */ },
findClient: async (clientId) => { /* 查找客户端逻辑 */ },
authConfig: {
passwordValidator: async (username, password) => {
// 验证用户名密码返回用户ID或null
}
}
});
```
### 使用HMAC算法需要提供密钥
```typescript
const provider = new OIDCProvider({
issuer: 'https://auth.example.com',
signingKey: 'your-secret-key', // HS256必须提供密钥
signingAlgorithm: 'HS256', // 可选默认为HS256
storage: storageAdapter,
findUser: async (userId) => { /* 查找用户逻辑 */ },
findClient: async (clientId) => { /* 查找客户端逻辑 */ },
authConfig: {
passwordValidator: async (username, password) => {
// 验证用户名密码返回用户ID或null
}
}
});
```
## 密钥生成时机
- **懒加载**密钥对将在首次调用需要签名的方法时自动生成如生成token、获取JWKS等
- **一次生成**每个Provider实例只会生成一次密钥对后续调用会复用相同的密钥
- **控制台输出**:自动生成密钥对时会在控制台输出确认信息
## 注意事项
1. **生产环境建议**:在生产环境中,建议提前生成并持久化密钥对,而不是每次启动时重新生成
2. **HS256算法**使用HS256时仍然需要提供`signingKey`
3. **同步构造**:现在可以直接使用`new OIDCProvider()`构造函数,无需异步等待
4. **密钥轮换**:如果需要密钥轮换,可以使用`JWTUtils.generateRSAKeyPair()`或`JWTUtils.generateECDSAKeyPair()`方法生成新的密钥对
## 手动提供密钥对
如果你想手动提供密钥对:
```typescript
import { JWTUtils } from '@your-package/oidc-provider';
// 生成密钥对
const keyPair = await JWTUtils.generateRSAKeyPair('my-key-id');
const provider = new OIDCProvider({
issuer: 'https://auth.example.com',
signingKey: keyPair, // 手动提供密钥对
signingAlgorithm: 'RS256',
// ... 其他配置
});
```