Skip to main content

细粒度授权 (Permit)

数据库操作通常需要仔细控制谁可以访问或修改哪些数据。虽然 Prisma ORM 擅长数据建模和数据库访问,但它并不包含内置的授权功能。本指南介绍如何使用 @permitio/permit-prisma 扩展在 Prisma 应用中实现细粒度的授权。

¥Database operations often require careful control over who can access or modify which data. While Prisma ORM excels at data modeling and database access, it doesn't include built-in authorization capabilities. This guide shows how to implement fine-grained authorization in your Prisma applications using the @permitio/permit-prisma extension.

细粒度授权 (FGA) 可在粒度级别上对用户可以访问或修改的数据进行详细而精确的控制。如果没有适当的授权,你的应用可能会暴露敏感数据或允许未经授权的修改,从而造成安全漏洞。

¥Fine-grained authorization (FGA) provides detailed and precise control over what data users can access or modify at a granular level. Without proper authorization, your application might expose sensitive data or allow unauthorized modifications, creating security vulnerabilities.

访问控制模型

¥Access control models

此扩展支持 Permit.io 的三种访问控制模型:

¥This extension supports three access control models from Permit.io:

基于角色的访问控制 (RBAC)

¥Role-based Access Control (RBAC)

它是什么:用户被分配了具有预定义权限的角色(管理员、编辑者、查看者),以对资源类型执行操作。

¥What it is: Users are assigned roles (Admin, Editor, Viewer) with predefined permissions to perform actions on resource types.

示例:"编辑器" 角色可以更新系统中的任何文档。

¥Example: An "Editor" role can update any document in the system.

最适合:简单的权限结构,访问权限由工作职能或用户级别决定。

¥Best for: Simple permission structures where access is determined by job function or user level.

基于属性的访问控制 (ABAC)

¥Attribute-Based Access Control (ABAC)

它是什么:基于用户、资源或环境属性的访问决策。

¥What it is: Access decisions based on attributes of users, resources, or environment.

示例:

¥Examples:

  • 如果 user.department == document.department 允许访问

    ¥Allow access if user.department == document.department

  • 如果 document.status == "DRAFT" 允许更新

    ¥Allow updates if document.status == "DRAFT"

它如何与扩展程序配合使用:当 enableAttributeSync 启用时,资源属性会自动同步到 Permit.io 进行策略评估。

¥How it works with the extension: When enableAttributeSync is on, resource attributes are automatically synced to Permit.io for policy evaluation.

最适合:依赖于上下文或数据属性的动态规则。

¥Best for: Dynamic rules that depend on context or data properties.

基于关系的访问控制 (ReBAC)

¥Relationship-Based Access Control (ReBAC)

它是什么:基于用户与特定资源实例之间关系的权限。

¥What it is: Permissions based on relationships between users and specific resource instances.

示例:一个用户是文档 123 的 "所有者",但只是文档 456 的 "查看器"。

¥Example: A user is an "Owner" of document-123 but just a "Viewer" of document-456.

它如何与扩展程序配合使用:

¥How it works with the extension:

  • 资源实例同步到 Permit.io(使用 enableResourceSync: true

    ¥Resource instances are synced to Permit.io (with enableResourceSync: true)

  • 权限检查包括特定的资源实例 ID

    ¥Permission checks include the specific resource instance ID

最适合:协作应用,用户需要对同一资源类型的不同实例拥有不同的权限。

¥Best for: Collaborative applications where users need different permissions on different instances of the same resource type.

选择合适的模型

¥Choosing the right model

  • RBAC:当你需要简单的基于角色的访问控制时

    ¥RBAC: When you need simple, role-based access control

  • ABAC:当决策取决于数据属性或上下文信息时

    ¥ABAC: When decisions depend on data properties or contextual information

  • ReBAC:当用户需要在不同实例上设置不同权限时

    ¥ReBAC: When users need different permissions on different instances

用法

¥Usage

先决条件

¥Prerequisites

在使用 Prisma 实现细粒度授权之前,请确保你已:

¥Before implementing fine-grained authorization with Prisma, make sure you have:

  • 一个包含现有模型和查询的 Prisma 应用

    ¥A Prisma application with existing models and queries

  • 了解授权概念

    ¥Basic understanding of authorization concepts

  • 已安装 Node.js 和 npm

    ¥Node.js and npm installed

安装

¥Installation

与 Prisma 客户端一起安装扩展:

¥Install the extension alongside Prisma Client:

npm install @permitio/permit-prisma @prisma/client

你还需要注册一个 Permit 账户 来定义你的授权策略。

¥You'll also need to sign up for a Permit account to define your authorization policies.

注意:确保 Permit PDP 容器正在运行。建议使用 Docker 运行它,以获得更好的性能、安全性和可用性。有关说明,请参阅 Permit 文档:将 Permit 部署到生产环境PDP 概述

¥Note:\ Ensure that the Permit PDP container is running. It is recommended to run it using Docker for better performance, security, and availability. For instructions, refer to the Permit documentation: Deploy Permit to Production and PDP Overview.

基本设置

¥Basic setup

首先,使用 Permit 扩展程序扩展你的 Prisma 客户端:

¥First, extend your Prisma Client with the Permit extension:

import { PrismaClient } from "@prisma/client";
import { createPermitClientExtension } from "@permitio/permit-prisma";

const prisma = new PrismaClient().$extends(
createPermitClientExtension({
permitConfig: {
token: process.env.PERMIT_API_KEY, // Your Permit API key
pdp: "http://localhost:7766", // PDP address (local or cloud)
},
enableAutomaticChecks: true // Automatically enforce permissions
})
);

实现 RBAC(基于角色的访问控制)

¥Implementing RBAC (Role-Based Access Control)

RBAC 使用角色来确定访问权限。例如,"管理员" 角色可以执行所有操作,而 "查看器" 角色只能读取数据。

¥RBAC uses roles to determine access permissions. For example, "Admin" roles can perform all actions while "Viewer" roles can only read data.

  1. 在 Permit.io 仪表板中定义资源和操作:

    ¥Define resources and actions in Permit.io dashboard:

    • 创建与你的 Prisma 模型匹配的资源(例如 "document")

      ¥Create resources matching your Prisma models (e.g., "document")

    • 定义操作(例如,"create"、"read"、"update"、"delete")

      ¥Define actions (e.g., "create", "read", "update", "delete")

    • 创建具有权限集的角色(例如 "admin"、"editor"、"viewer")

      ¥Create roles with permission sets (e.g., "admin", "editor", "viewer")

  2. 在你的代码中设置活动用户:

    ¥Set the active user in your code:

// Set the current user context before performing operations
prisma.$permit.setUser("john@example.com");

// All subsequent operations will be checked against this user's permissions
const documents = await prisma.document.findMany();

实现 ABAC(基于属性的访问控制)

¥Implementing ABAC (Attribute-Based Access Control)

ABAC 通过考虑用户属性、资源属性和上下文来扩展访问控制。

¥ABAC extends access control by considering user attributes, resource attributes, and context.

  1. 配置 ABAC 扩展:

    ¥Configure the extension for ABAC:

const prisma = new PrismaClient().$extends(
createPermitClientExtension({
permitConfig: { token: process.env.PERMIT_API_KEY, pdp: "http://localhost:7766" },
enableAutomaticChecks: true,
})
);
  1. 设置用户属性:

    ¥Set user with attributes:

prisma.$permit.setUser({
key: "doctor@hospital.com",
attributes: { department: "cardiology" }
});

// Will succeed only if user department matches record department (per policy)
const records = await prisma.medicalRecord.findMany({
where: { department: "cardiology" }
});

实现 ReBAC(基于关系的访问控制)

¥Implementing ReBAC (Relationship-Based Access Control)

ReBAC 根据用户与特定资源实例之间的关系建模权限。

¥ReBAC models permissions based on relationships between users and specific resource instances.

  1. 配置 ReBAC 扩展:

    ¥Configure the extension for ReBAC:

const prisma = new PrismaClient().$extends(
createPermitClientExtension({
permitConfig: { token: process.env.PERMIT_API_KEY, pdp: "http://localhost:7766" },
accessControlModel: "rebac",
enableAutomaticChecks: true,
enableResourceSync: true, // Sync resource instances with Permit.io
enableDataFiltering: true // Filter queries by permissions
})
);
  1. ** 访问实例特定资源:**

    ¥** Access instance-specific resources:**

prisma.$permit.setUser("owner@example.com");

// Will only succeed if the user has permission on this specific file
const file = await prisma.file.findUnique({
where: { id: "file-123" }
});

手动权限检查

¥Manual permission checks

为了获得更多控制,你可以执行显式权限检查:

¥For more control, you can perform explicit permission checks:

// Check if user can update a document
const canUpdate = await prisma.$permit.check(
"john@example.com", // user
"update", // action
"document" // resource
);

if (canUpdate) {
await prisma.document.update({
where: { id: "doc-123" },
data: { title: "Updated Title" }
});
}

// Or enforce permissions (throws if denied)
await prisma.$permit.enforceCheck(
"john@example.com",
"delete",
{ type: "document", key: "doc-123" }
);

常见用例

¥Common use cases

以下是一些需要细粒度授权的常见场景:

¥Here are some common scenarios where fine-grained authorization is valuable:

  • 多租户应用:隔离不同客户之间的数据

    ¥Multi-tenant applications: Isolate data between different customers

  • 医疗保健应用:确保只有授权人员才能访问患者数据

    ¥Healthcare applications: Ensure patient data is only accessible to authorized staff

  • 协作平台:授予共享资源的不同权限

    ¥Collaborative platforms: Grant different permissions on shared resources

  • 内容管理系统:控制谁可以发布、编辑或查看内容

    ¥Content management systems: Control who can publish, edit, or view content

概括

¥Summary

通过将 @permitio/permit-prisma 扩展与你的 Prisma ORM 应用集成,你可以实现复杂的授权策略来保护你的数据并确保用户只能访问他们被允许查看的内容。该扩展支持所有主流授权模型(RBAC、ABAC、ReBAC),并提供自动和手动权限执行。

¥By integrating the @permitio/permit-prisma extension with your Prisma ORM application, you can implement sophisticated authorization policies that protect your data and ensure users only access what they're permitted to see. The extension supports all major authorization models (RBAC, ABAC, ReBAC) and provides both automatic and manual permission enforcement.

下一步

¥Next steps