@ granjs/ 客户端
Grant授权平台的浏览器SDK. 提供轻量级客户端,用于使用React hooks和组件进行许可检查,用于有条件的UI渲染.
联合国 客户端 SDK 在官方的文档.
特征
- 基于 REST 的 API - 本地用途
fetch,不需要图形QL客户端 - 自动刷新令牌 - 处理401个错误,并更新和重试
- 内建缓存 - 配置基于 TTL 的缓存以尽量减少API 调用
- 多租户支助 - 会话符号动态范围切换
- 反应整合 - 用于申报许可检查的钩和组件
- 类型脚本 - 全面类型的安全,类型来自
@grantjs/schema
安装
npm install @grantjs/client
# or
pnpm add @grantjs/client
# or
yarn add @grantjs/client
快速启动
1. 创建客户
import { GrantClient } from '@grantjs/client';
const grant = new GrantClient({
apiUrl: 'https://api.your-app.com',
getAccessToken: () => localStorage.getItem('accessToken'),
// Cookie-based refresh: your callback calls POST /api/auth/refresh with credentials: 'include',
// then updates app token storage. Refresh token is in HttpOnly cookie; response body has only accessToken.
onRefreshWithCredentials: async () => {
const res = await fetch('https://api.your-app.com/api/auth/refresh', {
method: 'POST',
credentials: 'include',
});
if (!res.ok) return false;
const { data } = await res.json();
if (data?.accessToken) {
localStorage.setItem('accessToken', data.accessToken);
return true;
}
return false;
},
onTokenRefresh: (tokens) => {
localStorage.setItem('accessToken', tokens.accessToken);
// tokens.refreshToken may be undefined when using cookie-based refresh
},
onUnauthorized: () => {
window.location.href = '/login';
},
});
// Check permission
const canEdit = await grant.can('Document', 'Update');
2. 反应设置
包装您的应用程序 GrantProvider 与您的认证库合并 :
'use client';
import { useMemo } from 'react';
import { GrantProvider, type GrantClientConfig } from '@grantjs/client/react';
import { useAuthStore } from '@/stores/auth.store';
export function AppProviders({ children }: { children: React.ReactNode }) {
const config = useMemo<GrantClientConfig>(
() => ({
apiUrl: process.env.NEXT_PUBLIC_API_URL!,
getAccessToken: () => useAuthStore.getState().accessToken,
// Cookie-based refresh: POST /api/auth/refresh with credentials: 'include', then update store
onRefreshWithCredentials: async () => {
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/auth/refresh`, {
method: 'POST',
credentials: 'include',
});
if (!res.ok) return false;
const { data } = await res.json();
if (data?.accessToken) {
useAuthStore.getState().setAccessToken(data.accessToken);
return true;
}
return false;
},
onTokenRefresh: (tokens) => {
useAuthStore.getState().setAccessToken(tokens.accessToken);
},
onUnauthorized: () => {
useAuthStore.getState().logout();
if (typeof window !== 'undefined') {
window.location.href = '/auth/login';
}
},
cache: {
ttl: 5 * 60 * 1000, // 5 minutes
prefix: 'grant',
},
}),
[]
);
return <GrantProvider config={config}>{children}</GrantProvider>;
}
3. 有范围的使用
对于多租户的应用程序,通过特定上下文检查权限的范围:
'use client';
import { useGrant } from '@grantjs/client/react';
import { Tenant } from '@grantjs/schema';
interface OrganizationActionsProps {
organization: { id: string; name: string };
}
export function OrganizationActions({ organization }: OrganizationActionsProps) {
// Scope permissions to this specific organization
const scope = { tenant: Tenant.Organization, id: organization.id };
// Check permissions - these call POST /api/auth/is-authorized
const canUpdate = useGrant('Organization', 'Update', { scope });
const canDelete = useGrant('Organization', 'Delete', { scope });
// Hide component entirely if user has no permissions
if (!canUpdate && !canDelete) {
return null;
}
return (
<div>
{canUpdate && <button>Edit</button>}
{canDelete && <button>Delete</button>}
</div>
);
}
4. 使用组件
import { GrantGate } from '@grantjs/client/react';
import { Tenant } from '@grantjs/schema';
function Dashboard({ projectId }: { projectId: string }) {
const scope = { tenant: Tenant.Organization, id: projectId };
return (
<div>
{/* Hide if no permission */}
<GrantGate resource="Analytics" action="Read" scope={scope}>
<AnalyticsWidget />
</GrantGate>
{/* Show fallback if denied */}
<GrantGate
resource="Settings"
action="Update"
scope={scope}
fallback={<p>Contact admin for access</p>}
>
<SettingsPanel />
</GrantGate>
{/* With loading state */}
<GrantGate resource="Report" action="Create" scope={scope} loading={<Spinner />}>
<ExportButton />
</GrantGate>
</div>
);
}
API 参考
赠与客户端
const grant = new GrantClient(config: GrantClientConfig);
配置
interface GrantClientConfig {
apiUrl: string;
getAccessToken?: () => string | null | Promise<string | null>;
/** Called after cookie-based refresh; use to update app token storage. `tokens.refreshToken` may be undefined. */
onTokenRefresh?: (tokens: AuthTokens) => void | Promise<void>;
onUnauthorized?: () => void;
/** Cookie-based refresh on 401: call POST /api/auth/refresh with credentials: 'include', update token, return true on success. */
onRefreshWithCredentials?: () => Promise<boolean>;
fetch?: typeof fetch;
credentials?: RequestCredentials; // default: 'include'
cache?: { ttl?: number; prefix?: string };
}
方法
// Permission checks
grant.can(resource, action, options?): Promise<boolean>
grant.hasPermission(resource, action, options?): Promise<boolean> // Alias
grant.isAuthorized(resource, action, options?): Promise<AuthorizationResult>
// Cache management
grant.clearCache(): void
grant.clearScopeCache(scope?): void
反应钩
useGrant(resource, action, options?)
默认返回布尔或对象 isGranted 财务报告和审定财务报表 isLoading 何时 returnLoading: true。 。 。 .
默认( 布尔 ) :
import { useGrant } from '@grantjs/client/react';
import { Tenant } from '@grantjs/schema';
const canEdit = useGrant('Document', 'Update', {
scope: { tenant: Tenant.Organization, id: orgId },
});
return <div>{canEdit && <EditButton />}</div>;
装入状态 :
const { isGranted, isLoading } = useGrant('Document', 'Update', {
scope: { tenant: Tenant.Organization, id: orgId },
returnLoading: true,
});
if (isLoading) return <Spinner />;
if (!isGranted) return null;
return <EditButton />;
钩子选项
interface UseGrantOptions {
scope?: Scope; // Multi-tenant scope override
enabled?: boolean; // Skip check if false (default: true)
useCache?: boolean; // Use cached result (default: true)
returnLoading?: boolean; // Return object with isGranted and isLoading (default: false)
}
interface UseGrantResult {
isGranted: boolean; // Whether the user is granted permission
isLoading: boolean; // Whether the permission check is loading
}
反应组件
<GrantGate>
<GrantGate
resource="Resource"
action="Action"
scope={{ tenant: Tenant.Organization, id: '...' }} // Optional
fallback={<FallbackComponent />} // Optional
loading={<LoadingSpinner />} // Optional
>
<ProtectedContent />
</GrantGate>
多十年范围覆盖
Grant平台支持有动态范围切换的多租户授权:
- 会话符号: 可按请求时间覆盖范围(用户在组织之间切换)
- API 密钥符号: 使用其嵌入范围( 无法覆盖)
import { useGrant } from '@grantjs/client/react';
import { Tenant } from '@grantjs/schema';
// User is viewing Organization A
const scopeA = { tenant: Tenant.Organization, id: 'org-a-id' };
const canEditA = useGrant('Project', 'Update', { scope: scopeA });
// User switches to Organization B
const scopeB = { tenant: Tenant.Organization, id: 'org-b-id' };
const canEditB = useGrant('Project', 'Update', { scope: scopeB });
现有租户类型(来自 @grantjs/schema:
enum Tenant {
System = 'system',
Account = 'account',
Organization = 'organization',
AccountProject = 'accountProject',
OrganizationProject = 'organizationProject',
ProjectUser = 'projectUser',
// ... and more
}
缓存
客户端缓存默认结果( 5分 TTL) 。 你可以这样:
// Configure TTL
const grant = new GrantClient({
apiUrl: '...',
cache: { ttl: 10 * 60 * 1000 }, // 10 minutes
});
// Bypass cache for a specific check
const fresh = await grant.can('Resource', 'Action', { useCache: false });
// Clear all cache
grant.clearCache();
// Clear cache for a specific scope
grant.clearScopeCache({ tenant: Tenant.Organization, id: orgId });
认证流程
- 访问令牌 发送通过
Authorization: Bearer <token>(当getAccessToken页:1. - 饼干 默认情况下包含在内(
credentials: 'include') (中文(简体) ). - 打开 401 (中文(简体) ),客户端使用 仅基于饼干的刷新 (没有基于身体的安全刷新):
- 若为
onRefreshWithCredentials已经设定,它叫做。 你该回电了POST /api/auth/refresh与credentials: 'include',读取新的accessToken从响应机构,更新您的存储,然后返回true在成功方面. - 成功时,客户端重试原始请求;您也可以使用
onTokenRefresh以同步符号状态. - 失败或失败时
onRefreshWithCredentials未设定,onUnauthorized()称为(例如重定向到登录). - 刷新符号生活在 HttpOnly cookie; API 只返回
accessToken在更新的反应机构.
- 若为
发展说明
反应严格模式
在开发中, 启用了 React Print 模式( 默认在 Next.js 13+), 您将看到 2个API电话 每个权限检查。 这是预期的行为:
- 组件挂载 —— 效果运行 —— API呼叫 # 1
- 严格模式卸载组件
- 组件重载 → 效果运行 → API呼叫 # 2
这只在发展过程中发生。 生产建设一呼而起.
稳定范围
钩子自动处理范围对象参考变化. 你不需要记住瞄准器:
// This is fine - hooks compare by value, not reference
const scope = { tenant: Tenant.Organization, id: organization.id };
const canEdit = useGrant('Resource', 'Action', { scope });
类型脚本
包括全部类型的定义。 从包中导入类型或从中再出口 @grantjs/schema数字 :
import type {
GrantClientConfig,
AuthorizationResult,
Permission,
Resource,
Scope,
Tenant,
} from '@grantjs/client';
// Or import Tenant enum directly from schema
import { Tenant } from '@grantjs/schema';
捐款
欢迎捐款! 请看 主要仓库 捐款准则.
支助
- 文档: 见 主要赠款文件
- 问题: 报告错误或请求特性 GitHub 问题
- 产品账户帮助( A)数字 : 支持@ granjs.org
- 安全脆弱性: 跟着 警卫 (达到) 工程学@ granjs.org(中文(简体) )
许可证
麻省理工学院