@ granjs/ 服务器
格兰特授权平台的服务器 SDK. 提供中间软件和警卫 快递, (中文(简体) ), 快捷化, (中文(简体) ), 网点JS,以及 下一个.js 应用.
联合国 服务器 SDK 在官方的文档.
特征
- 基于 REST 的 API - 本地用途
fetch,不需要图形QL客户端 - 框架整合 - 捷运(
grant()),快捷化(grant()页:1@Grant+ 键GrantGuard),下册.js (withGrant()(中文(简体) ) - 调试 - 支持授权页眉和饼干
- 资源解决器 - 条件评估的可选资源分辨率
- 基于JWT的范围 - 范围取自象征性要求(API-key / 客户端- 秘密流); 不使用请求的会话类范围
- 类型脚本 - 全面类型安全,类型来自
@grantjs/schema - 常规 - 使用任何许可模式(使用简单的字符串进行资源/行动)
安装
npm install @grantjs/server
# or
pnpm add @grantjs/server
# or
yarn add @grantjs/server
实例
每个框架的最小可运行应用 examples/ 并共享相同的 CRUD 表面(文件:Get, POST, PUT, PATCH, DELETE). 从回波根:
pnpm install
pnpm --filter @grantjs/server build
cd packages/@grantjs/server/examples/express # or fastify, nextjs, nestjs
cp .env.example .env # set GRANT_API_URL and optionally GRANT_TOKEN
pnpm start
| 示例 | 框架 | 使用量 |
|---|---|---|
express | 快递 | grant(client, { resource, action }) 中间软件 |
fastify | 快捷化 | grant(client, { resource, action }) 前汉德勒 |
nextjs | 下一个.js | withGrant(client, { resource, action }, handler) aPI线路 |
nestjs | 网点JS | @Grant(resource, action) + 键 GrantGuard, (中文(简体) ), GrantModule |
见 实例/README.md 为先决条件,路径,和卷曲命令.
快速启动
1. 创建客户
import { GrantClient } from '@grantjs/server';
// Basic configuration (uses Authorization header or cookies)
const grantClient = new GrantClient({
apiUrl: 'https://api.grant.com',
});
// With cookie-based auth
const grantClient = new GrantClient({
apiUrl: 'https://api.grant.com',
cookieName: 'grant-access-token', // Default: 'grant-access-token'
});
// With custom token extraction
const grantClient = new GrantClient({
apiUrl: 'https://api.grant.com',
getToken: (request) => {
// Custom logic to extract token from request
const req = request as { headers?: { 'x-api-key'?: string } };
return req.headers?.['x-api-key'] || null;
},
});
2. 中快件
import express from 'express';
import { grant } from '@grantjs/server/express';
const app = express();
const grantClient = new GrantClient({ apiUrl: 'https://api.grant.com' });
// Basic usage
app.get(
'/organizations',
grant(grantClient, {
resource: 'Organization',
action: 'Query',
}),
async (req, res) => {
// User is authorized, proceed with handler
res.json({ organizations: [] });
}
);
// With resource resolver for condition evaluation
app.patch(
'/projects/:id',
grant(grantClient, {
resource: 'Project',
action: 'Update',
resourceResolver: async ({ resourceSlug, request }) => {
// Resolve the project resource for condition evaluation
const projectId = (request as any).params.id;
const project = await getProjectById(projectId);
return project ? { id: project.id, ownerId: project.ownerId } : null;
},
}),
async (req, res) => {
// User is authorized, proceed with handler
res.json({ success: true });
}
);
3. 简化插件
import Fastify from 'fastify';
import { grantPlugin, grant } from '@grantjs/server/fastify';
import { GrantClient } from '@grantjs/server';
const fastify = Fastify();
// Register the plugin (decorates fastify.grant)
await fastify.register(grantPlugin, {
apiUrl: 'https://api.grant.com',
cookieName: 'grant-access-token',
});
// Use preHandler hook
fastify.get(
'/organizations',
{
preHandler: grant(fastify.grant, {
resource: 'Organization',
action: 'Query',
}),
},
async (request, reply) => {
return { organizations: [] };
}
);
// With resource resolver
fastify.patch(
'/projects/:id',
{
preHandler: grant(fastify.grant, {
resource: 'Project',
action: 'Update',
resourceResolver: async ({ resourceSlug, request }) => {
const projectId = (request.params as { id: string }).id;
const project = await getProjectById(projectId);
return project ? { id: project.id, ownerId: project.ownerId } : null;
},
}),
},
async (request, reply) => {
return { success: true };
}
);
4. Next.js (App路由器)
// app/api/documents/route.ts
import { NextResponse } from 'next/server';
import { withGrant } from '@grantjs/server/next';
import { GrantClient } from '@grantjs/server';
const grantClient = new GrantClient({ apiUrl: process.env.GRANT_API_URL! });
export const GET = withGrant(grantClient, { resource: 'Document', action: 'Query' }, async () =>
NextResponse.json({ data: [] })
);
export const POST = withGrant(
grantClient,
{ resource: 'Document', action: 'Create' },
async (request) => {
const body = await request.json();
return NextResponse.json({ data: { title: body?.title ?? 'Untitled' } }, { status: 201 });
}
);
5. 雀巢协会
// app.module.ts
import { GrantModule } from '@grantjs/server/nest';
@Module({
imports: [
GrantModule.forRoot({
apiUrl: process.env.GRANT_API_URL!,
getToken: (req: any) => req.headers?.authorization?.replace?.('Bearer ', '') ?? null,
}),
],
})
export class AppModule {}
// documents.controller.ts
import { Grant, GrantGuard } from '@grantjs/server/nest';
@Controller('documents')
export class DocumentsController {
@Get()
@Grant('Document', 'Query')
@UseGuards(GrantGuard)
list() {
return { data: [] };
}
@Post()
@Grant('Document', 'Create')
@UseGuards(GrantGuard)
create(@Body() body: { title?: string }) {
return { data: { title: body?.title ?? 'Untitled' } };
}
}
登记册 GrantGuard 作为您的特性模块中的提供者( 例如) . providers: [GrantGuard])所以巢会注射 GrantClient。见 examples/nestjs 一个完整的应用程序.
API 参考
赠与客户端
const grantClient = new GrantClient(config: GrantServerConfig);
配置
interface GrantServerConfig {
// Required
apiUrl: string;
// Optional
cookieName?: string; // Default: 'grant-access-token'
getToken?: (request: unknown) => string | null | Promise<string | null>;
fetch?: typeof fetch;
credentials?: RequestCredentials;
}
方法
// Permission checks
grantClient.isGranted(resource, action, options?, request?): Promise<boolean>
grantClient.isAuthorized(resource, action, options?, request?): Promise<AuthorizationResult>
// Token extraction
grantClient.getTokenFromRequest(request): Promise<string | null>
表达式中件
grant(client, options)
创建 Express 中间软件, 在进行前检查授权 .
选项 :
interface GrantOptions {
resource: string; // Resource slug (e.g., "Organization", "Project", "Document")
action: string; // Action name (e.g., "Query", "Create", "Update", "Delete")
resourceResolver?: ResourceResolver; // Resource resolution for conditions
}
行为:
- 回返
401 Unauthorized如果找不到任何符号 - 回返
404 Not Found如果资源解析器返回为无效 - 回返
403 Forbidden如果用户没有权限 - 电话
next()如经核准 - 附 录
authorization结果是req.authorization用于下游用途 - 授权范围取自JWT(如API-key / 客户端-保密令牌);不取自请求
快捷插件
grantPlugin(fastify, options)
注册一个用于装饰实例的快取插件 fastify.grant (GrantClient) (英语).
选项 :
与 GrantServerConfig - 看见没 授予客户端配置 见上文.
用法 :
await fastify.register(grantPlugin, {
apiUrl: 'https://api.grant.com',
cookieName: 'grant-access-token',
});
// Now fastify.grant is available
const canEdit = await fastify.grant.isGranted('Document', 'Update', undefined, request);
grant(client, options)
创建快取 preHandler 检查授权后再开始.
选项 :
与快车相同 GrantOptions - 见上文.
行为:
- 回返
401 Unauthorized如果找不到任何符号 - 回返
404 Not Found如果资源解析器返回为无效 - 回返
403 Forbidden如果用户没有权限 - 附 录
authorization结果是request.authorization用于下游用途 - 授权范围取自联合WT;不取自请求
Next.js (App路由器) (英语)
withGrant(client, options, handler)
以 Grant 的授权包入 App 路由器路由处理器 。 用于 GET, (中文(简体) ), POST, (中文(简体) ), PUT, (中文(简体) ), PATCH, (中文(简体) ), DELETE 内 app/api/.../route.ts。 。 。 .
选项 : 与快车相同 GrantOptions (资源,动作,可选资源解析器).
行为: 回返 401 编号 : 404 编号 : 403 失败时的响应; 用 (request, { authorization }) 在成功方面。 与Next.js 13–16相兼容.
网点JS
GrantModule.forRoot(config)
提供全球模块 GrantClient 用于注射。 导入 AppModule。 。 。 .
@Grant(resource, action) 编号 : Grant(resource, action)
设置资源/行动元数据 GrantGuard与 @UseGuards(GrantGuard) 关于控制器方法.
GrantGuard
读取选项的守护者 @Grant() 元数据(或带有可选的清晰构建器选项) resourceResolver) (中文(简体) ). 注册为提供者(例如:. providers: [GrantGuard])所以巢会注射 GrantClient 财务报告和审定财务报表 Reflector出口 GRANT_CLIENT 财务报告和审定财务报表 GRANT_OPTIONS_KEY 用于高级用途.
Token 提取器
客户端支持多个符取出方法(按优先排序):
- 自定义
getToken函数 (如果有的话) - 授权页眉数字 :
Authorization: Bearer <token> - 饼干: Cookie 名称由
cookieName配置( 默认 ):grant-access-token(中文(简体) )
资源解析器
资源解析器是解决用于条件评价的资源数据的可选功能. 范围不从中间器件传递(取自API一侧的JWT).
const resourceResolver: ResourceResolver = async ({ resourceSlug, request }) => {
// Fetch resource from database
const resource = await getResource(resourceSlug, request);
// Return resource data for condition evaluation
// e.g., { id: '...', ownerId: '...', status: 'active' }
return resource ? { id: resource.id, ownerId: resource.ownerId } : null;
};
如果解析器返回 null,中间软件返回 404 Not Found。 。 。 .
开发/ 调试
设定 DEBUG_GRANT=1 在环境(例如: .env)启用所有集成(Express, Fastify, Next, Nest)的请求/结果日志. 日志包括资源、行动和授权/拒绝说明理由.
处理错误
用于优等错误处理的软件包导出错误分类 :
import {
AuthenticationError, // 401
AuthorizationError, // 403
BadRequestError, // 400
NotFoundError, // 404
} from '@grantjs/server';
try {
await grantClient.isAuthorized('resource', 'action', undefined, request);
} catch (error) {
if (error instanceof AuthenticationError) {
// Handle 401
} else if (error instanceof AuthorizationError) {
// Handle 403
}
}
类型脚本
完整类型的定义包括:
import type {
GrantServerConfig,
AuthorizationResult,
PermissionCheckOptions,
Scope,
ResourceResolver,
} from '@grantjs/server';
import { Tenant } from '@grantjs/schema';
与 @ granjs/ 客户比较
服务器软件包( E)@grantjs/server)设计为: 服务器侧 Node.js应用程序,而客户端软件包(@grantjs/client用于 浏览器 应用.
密钥差异 :
| 特性 | @ granjs/ 服务器 | @ granjs/ 客户端 |
|---|---|---|
| 目标 | 节点.js 服务器 | 浏览器应用程序 |
| 缓存 | 否(由API处理) | 是(5min TTL) |
| 调试源 | 请求对象 | 回调函数 |
| 框架支助 | 捷运,快活,雀巢JS,Next.js | 反应, Vue, Svelte, 角 |
| API 密码 | grant() (快递/快递), withGrant() (下个), @Grant (节日) | useGrant() 钩子 |
| 处理错误 | HTTP 状态代码 | 布尔返回 |
| 资源/行动 | 平面字符串( 基因) | 平面字符串( 基因) |
何时使用 :
- @ granjs/ 服务器: 保护 API 路由, GraphQL 解析器, 服务器侧中件
- @ granjs/ 客户端: 有条件的 UI 渲染, 客户端许可检查
许可证
麻省理工学院