0.0.8 • Published 6 months ago

@zhaoanke/authz-node v0.0.8

Weekly downloads
-
License
MIT
Repository
github
Last release
6 months ago

Node.js Authz Client

一个轻量级的授权(Authorization)客户端库。

npm version License: MIT

安装

npm install @zhaoanke/authz-node
# 或
yarn add @zhaoanke/authz-node

环境变量配置

创建 .env 文件并配置以下环境变量:

# Authz Configuration
AUTHZ_APPID=authz
AUTHZ_LOGIN_TYPE=password
AUTHZ_GRANT_TYPE=authorization_code

# API Configuration
AUTHZ_API_URL=http://0.0.0.0:8080

# Secrets
AUTHZ_APP_SECRET=your-app-secret            # 用于认证的 APP 秘钥
AUTHZ_ENCRYPTION_SECRET=your-encrypt-secret  # 用于加密的加密秘钥

使用方法

import { AuthzClient } from '@zhaoanke/authz-node';

const client = new AuthzClient({
  baseUrl: 'https://your-authz-server.com',
  apiKey: 'your-api-key'
});

// 检查权限
const hasAccess = await client.check({
  subject: 'user:123',
  action: 'read',
  resource: 'document:456'
});

// 批量检查权限
const results = await client.batchCheck([
  {
    subject: 'user:123',
    action: 'read',
    resource: 'document:456'
  },
  {
    subject: 'user:123',
    action: 'write',
    resource: 'document:789'
  }
]);

API 文档

创建客户端

const client = new AuthzClient(options: AuthzClientOptions)

选项

  • baseUrl: 授权服务器的基础URL
  • apiKey: API密钥
  • timeout: 请求超时时间(毫秒),默认5000ms

OAuth2 认证

getToken(request: OAuth2TokenRequest): Promise

获取访问令牌:

// 使用授权码获取令牌
const tokenResponse = await client.getToken({
  grant_type: 'authorization_code',
  code: 'authorization_code',
  redirect_uri: 'https://your-app.com/callback'
});

// 使用刷新令牌
const newTokenResponse = await client.getToken({
  grant_type: 'refresh_token',
  refresh_token: 'refresh_token'
});

authorize(request: OAuth2AuthorizeRequest): Promise

请求授权:

const redirectUrl = await client.authorize({
  response_type: 'code',
  client_id: 'your_client_id',
  redirect_uri: 'https://your-app.com/callback',
  scope: 'read write',
  state: 'random_state'
});

authenticate(token: string): Promise

验证身份:

const authResponse = await client.authenticate('access_token');

权限检查

check(query: CheckQuery): Promise

检查单个权限

batchCheck(queries: CheckQuery[]): Promise<boolean[]>

批量检查权限

错误处理

库会抛出类型化的错误,可以通过 AuthzError 来处理:

try {
  await client.check(query);
} catch (error) {
  if (error instanceof AuthzError) {
    console.error('授权错误:', error.message);
  }
}
0.0.3

7 months ago

0.0.8

6 months ago

0.0.5

7 months ago

0.0.4

7 months ago

0.0.7

7 months ago

0.0.6

7 months ago

0.0.2

7 months ago