@paraview/auth-sdk
v1.0.1-rc.5
Published
Authentication SDK with support for password, OAuth, CAS login and MFA
Downloads
15
Readme
@paraview/auth-sdk
一个功能强大的身份认证 SDK,支持多种登录方式和多因素认证 (MFA)。
✨ 特性
- 🔐 多种登录方式:支持密码、OAuth、CAS 等登录方式
- 🛡️ 多因素认证 (MFA):支持 OTP、SMS、Radius 等 MFA 方法
- 🌐 跨平台支持:支持浏览器、Node.js、React 等多种环境
- 📦 多种模块格式:提供 ES6、CommonJS、UMD 等多种格式
- 🔧 灵活配置:支持自定义端点、请求头等配置
- 📝 TypeScript 支持:完整的 TypeScript 类型定义
- 🚀 易于使用:简洁的 API 设计,快速集成
📦 安装
npm install @paraview/auth-sdk🚀 快速开始
基础使用
import { createAuthSDK } from '@paraview/auth-sdk';
// 初始化 SDK
const authSDK = createAuthSDK({
baseURL: 'https://your-api-server.com',
timeout: 10000
});
// 用户登录
const loginResult = await authSDK.login({
type: 'password',
username: '[email protected]',
password: 'password123'
});
if (loginResult.success) {
console.log('登录成功:', loginResult.userInfo);
// 如果需要 MFA 验证
if (loginResult.requiresMFA) {
const mfaResult = await authSDK.verifyMFA({
code: '123456',
methodType: 'OTP'
});
console.log('MFA 验证结果:', mfaResult);
}
}React 中使用
import React, { useState } from 'react';
import { createAuthSDK } from '@paraview/auth-sdk';
const authSDK = createAuthSDK({
baseURL: 'https://your-api-server.com'
});
function LoginComponent() {
const [user, setUser] = useState(null);
const handleLogin = async (credentials) => {
try {
const result = await authSDK.login(credentials);
if (result.success) {
setUser(result.userInfo);
}
} catch (error) {
console.error('登录失败:', error);
}
};
return (
<div>
{user ? (
<div>欢迎, {user.username}!</div>
) : (
<LoginForm onLogin={handleLogin} />
)}
</div>
);
}📚 API 文档
初始化配置
interface SDKConfig {
baseURL: string; // API 服务器地址
timeout?: number; // 请求超时时间 (ms)
apiKey?: string; // API 密钥
headers?: Record<string, string>; // 自定义请求头
endpoints?: { // 自定义端点配置
passwordLogin?: EndpointConfig;
oauthLogin?: EndpointConfig;
mfaVerify?: EndpointConfig;
// ... 更多端点配置
};
}主要方法
🔐 用户认证
// 登录
login(request: LoginRequest): Promise<LoginResponse>
// 登出
logout(sessionId?: string): Promise<APIResponse<{ success: boolean }>>🛡️ 多因素认证 (MFA)
// MFA 验证
verifyMFA(request: MFAVerificationRequest): Promise<MFAVerificationResponse>
// 绑定 MFA 方法
bindMFA(request: MFABindRequest): Promise<MFABindResponse>
// 解绑 MFA 方法
unbindMFA(request: MFAUnbindRequest): Promise<MFAUnbindResponse>
// 获取用户 MFA 方法
getMFAMethods(userId: string): Promise<APIResponse<MFAMethod[]>>
// 获取用户绑定信息
getUserBindings(userId: string): Promise<APIResponse<MFABinding[]>>
// 获取可用认证方法
getAvailableAuthMethods(): Promise<APIResponse<AvailableMFAMethod[]>>登录类型
支持多种登录方式:
interface LoginRequest {
type: 'password' | 'oauth' | 'oauth_callback' | 'cas' | 'cas_validate';
// 密码登录
username?: string;
password?: string;
// OAuth 登录
provider?: 'google' | 'github' | 'microsoft' | 'facebook' | 'custom';
redirectUri?: string;
state?: string;
scopes?: string[];
// CAS 登录
service?: string;
casServerUrl?: string;
// 自定义端点
customEndpoint?: string;
customMethod?: 'GET' | 'POST';
}MFA 方法
支持多种 MFA 方法:
- OTP (One-Time Password): 基于时间的一次性密码
- SMS: 短信验证码
- Radius: Radius 服务器认证
🌐 多环境支持
浏览器环境
<!-- UMD 格式 -->
<script src="https://unpkg.com/@paraview/auth-sdk/dist/auth-sdk.umd.js"></script>
<script>
const sdk = AuthSDK.createAuthSDK({
baseURL: 'https://api.example.com'
});
</script>Node.js 环境
// ES Modules
import { createAuthSDK } from '@paraview/auth-sdk';
// CommonJS
const { createAuthSDK } = require('@paraview/auth-sdk');React/Vue/Angular
import { createAuthSDK } from '@paraview/auth-sdk';
const authSDK = createAuthSDK({
baseURL: process.env.REACT_APP_API_URL
});🔧 高级配置
自定义端点
const sdk = createAuthSDK({
baseURL: 'https://api.example.com',
endpoints: {
passwordLogin: { url: '/custom/login', method: 'POST' },
mfaVerify: { url: '/custom/mfa/verify', method: 'POST' },
logout: { url: '/custom/logout', method: 'DELETE' }
}
});自定义请求头
const sdk = createAuthSDK({
baseURL: 'https://api.example.com',
headers: {
'Authorization': 'Bearer your-token',
'X-Client-Version': '1.0.0',
'X-Custom-Header': 'custom-value'
}
});错误处理
try {
const result = await authSDK.login(credentials);
if (result.success) {
// 处理成功情况
console.log('登录成功:', result.userInfo);
} else {
// 处理业务逻辑错误
console.error('登录失败:', result.message);
}
} catch (error) {
// 处理网络错误、系统错误等
if (error.code === 'NETWORK_ERROR') {
console.error('网络错误:', error.message);
} else if (error.code === 'TIMEOUT') {
console.error('请求超时:', error.message);
} else {
console.error('未知错误:', error.message);
}
}📖 示例代码
查看 examples/ 目录获取完整的使用示例:
examples/sdk-demo.html- 浏览器直接使用示例examples/node-demo.cjs- Node.js CommonJS 示例examples/node-demo.mjs- Node.js ES Module 示例examples/es6-demo.js- ES6 模块示例examples/react-demo.tsx- React 组件示例
🛠️ 开发
构建项目
# 安装依赖
npm install
# 构建 SDK
npm run build
# 开发模式(自动重新构建)
npm run dev运行示例
# 运行 Node.js 示例
node examples/node-demo.mjs
# 在浏览器中打开 HTML 示例
open examples/sdk-demo.html📄 许可证
MIT
🤝 贡献
欢迎提交 Issue 和 Pull Request!
📞 支持
如果您在使用过程中遇到问题,请通过以下方式联系我们:
- 提交 Issue
- 发送邮件至:[email protected]
