@cedar-policy/authorization-for-expressjs

中文文档
0.3.0发布于 2026/05/08Apache-2.0TypeScriptESM + CJS构建来源已验证近 30 天下载 1万

Middlewares to authorize expressJS applications with Cedar

原始使用文档
文档目录12 节
  1. Features
  2. Installation
  3. Quick Start
  4. Prerequisites
  5. Setting up the integration
  6. Configuration Options
  7. ExpressAuthorizationMiddleware
  8. Complete Example
  9. Tools to generate schemas from OpenAPI specs and sample pol…
  10. Security
  11. License
  12. Publishing

Cedar Authorization for ExpressJS

A middleware package that enables Cedar-based authorization for Express.js applications. This package makes it easy to implement fine-grained authorization controls using Cedar policies while seamlessly integrating with your Express.js application's authentication system.

Features

  • 🔒 Cedar-based authorization middleware for Express.js
  • 🎯 Fine-grained access control with Cedar policies
  • 🔑 Seamless integration with OIDC/JWT authentication
  • ⚡ Optimized authorization checks
  • 🛠️ Customizable principal entity mapping
  • 🚫 Endpoint exclusion support
  • 📝 Configurable logging

Installation

npm install @cedar-policy/authorization-for-expressjs

Quick Start

Prerequisites

Before you implement the Express integration, ensure you have:

  • Node.js and npm installed
  • An Express.js application
  • An OpenID Connect (OIDC) identity provider (optional for testing)

Setting up the integration

Let's walk through how to secure your application APIs using Cedar with the new package for Express.

Step 1: Add the Cedar Authorization Middleware package

The Cedar Authorization Middleware package will be used to generate a Cedar schema, create sample authorization policies, and perform the authorization in your application.

npm i --save @cedar-policy/authorization-for-expressjs

Step 2: Generate Cedar schema from your APIs

A Cedar schema defines the authorization model for an application, including the entity types in the application and the actions users are allowed to take. We recommend defining a namespace for your schema. In this example, we use YourNamespace. Your policies are validated against this schema when you run the application.

The authorization-for-expressjs package can analyze the OpenAPI specification of your application and generate a Cedar schema. Specifically, the paths object is required in your specification.

If you don't have an OpenAPI specification, you can follow the quick instructions of the express-openapi-generator package to generate an OpenAPI specification.

You can generate a Cedar schema by running, replacing openapi.json with the file of your schema and YourNamespace with the namespace of our choice:

npx @cedar-policy/authorization-for-expressjs generate-schema --api-spec openapi.json --namespace YourNamespace --mapping-type SimpleRest

This will generate a schema file named v4.cedarschema.json in the package root.

Step 3: Define authorization policies

If no policies are configured, Cedar denies all authorization requests. We will add policies that grant access to APIs only for authorized user groups.

Generate sample Cedar policies:

npx @cedar-policy/authorization-for-expressjs generate-policies --schema v4.cedarschema.json

This will generate sample policies in the /policies directory. You can then customize these policies based on your use cases. For example:

// Defines permitted administrator user group actions
permit (
    principal in YourNamespace::UserGroup::"<userPoolId>|administrator",
    action,
    resource
);

// Defines permitted employee user group actions
permit (
    principal in YourNamespace::UserGroup::"<userPoolId>|employee",
    action in
        [YourNamespace::Action::"GET /resources",
         YourNamespace::Action::"POST /resources",
         YourNamespace::Action::"GET /resources/{resourceId}",
         YourNamespace::Action::"PUT /resources/{resourceId}"],
    resource
);

Note: If you specified an operationId in the OpenAPI specification, the action names defined in the Cedar Schema will use that operationId instead of the default <HTTP Method> /<PATH> format. In this case, ensure the naming of your Actions in your Cedar Policies matches the naming of your Actions in your Cedar Schema.

For large applications with complex authorization policies, it can be challenging to analyze and audit the actual permissions provided by the many different policies. Cedar also provides the Cedar Analysis CLI to help developers perform policy analysis on their policies.

Step 4: Update the application code to call Cedar and authorize API access

The application will use the Cedar middleware to authorize every request against the Cedar policies. First, add the package to the project and define the CedarInlineAuthorizationEngine and ExpressAuthorizationMiddleware. This block of code can be added to the top of the app.js file:

const { ExpressAuthorizationMiddleware, CedarInlineAuthorizationEngine } = require('@cedar-policy/authorization-for-expressjs');

const policies = [
    fs.readFileSync(path.join(__dirname, 'policies', 'policy_1.cedar'), 'utf8'),
    fs.readFileSync(path.join(__dirname, 'policies', 'policy_2.cedar'), 'utf8')
];

const cedarAuthorizationEngine = new CedarInlineAuthorizationEngine({
    staticPolicies: policies.join('\n'),
    schema: {
        type: 'jsonString',
        schema: fs.readFileSync(path.join(__dirname, 'v4.cedarschema.json'), 'utf8'),
    }
});

const expressAuthorization = new ExpressAuthorizationMiddleware({
    schema: {
        type: 'jsonString',
        schema: fs.readFileSync(path.join(__dirname, 'v4.cedarschema.json'), 'utf8'),
    },
    authorizationEngine: cedarAuthorizationEngine,
    principalConfiguration: {
        type: 'custom',
        getPrincipalEntity: principalEntityFetcher
    },
    skippedEndpoints: [
        {httpVerb: 'get', path: '/login'},
        {httpVerb: 'get', path: '/api-spec/v3'},
    ],
    logger: {
        debug: s => console.log(s),
        log: s => console.log(s),
    }
});

Next, add the Express Authorization middleware to the application:

const app = express();

app.use(express.json());
app.use(verifyToken());   // validate user token
// ... other pre-authz middlewares

app.use(expressAuthorization.middleware);

// ... other middlewares

Step 5: Add application code to configure the user

The Cedar authorizer requires user groups and attributes to authorize requests. The authorization middleware relies on the function passed to getPrincipalEntity in the initial configuration to generate the principal entity. You need to implement this function to generate the user entity:

async function principalEntityFetcher(req) {
    const user = req.user;   // it's common practice for the authn middleware to store the user info from the decoded token here
    const userGroups = user["groups"].map(userGroupId => ({
        type: 'PetStoreApp::UserGroup',
        id: userGroupId       
    }));
    return {
        uid: {
            type: 'PetStoreApp::User',
            id: user.sub
        },
        attrs: {
            ...user,
        },
        parents: userGroups 
    };
}

Configuration Options

ExpressAuthorizationMiddleware

The middleware constructor accepts an options object with the following properties:

  • schema: Cedar schema configuration. The schema is the structure of the entities and actions in your application.
    • type: Schema type ('jsonString' for now, 'cedar' coming soon)
    • schema: Cedar schema as a string, in the format dictated by type
  • authorizationEngine: The authorization engine for the application. Current options are:
    • Cedar - @cedar-policy/authorization-for-expressjs
    • Amazon Verified Permissions (AVP) - @verifiedpermissions/authorization-clients
    • Custom - Define your own authorization engine
  • skippedEndpoints: Array of endpoints to skip authorization checks. For example, endpoints that are meant to be open to everyone (eg. /login and /signup) or endpoints that will be protected with the more granular version of the middleware.
    • httpVerb: HTTP method in lowercase
    • path: Express route path template
  • contextConfiguration (optional): The context object passed in the Cedar-based authorization request.
  • logger: Logging configuration
    • debug: Debug log function
      Note - Debug loggers will log unsecure information, such as user tokens, and should never be used in production applications.
    • log: Standard log function
  • principalConfiguration: Configuration for mapping authenticated users to Cedar principals. It's a type union like so:
    | {type: 'identityToken'}
    | {type: 'accessToken'}
    | {
        type: 'custom',
        getPrincipalEntity: (req: Request) => Promise<Entity>,
    };

The identityToken and access Token types are for identity and access tokens, respectively. They pass the token itself as the principal and should be used with an AuthorizationEngine that does authentication AND authorization. For example, the AVPAuthorizationEngine provided by the verifiedpermissions/authorization-clients-js package which calls the Amazon Verified Permissions API IsAuthorizedWithToken.

The custom type is meant to be used with any AuthorizationEngine, and presumes you have done authentication before running the middleware.

Complete Example

Check out the examples directory for a complete implementation of a protected API using this middleware.

Tools to generate schemas from OpenAPI specs and sample policies

These tools exist a different package, called @cedar-policy/cedar-authorization repo. For details on how they work, see that package's readme.

Security

See CONTRIBUTING for more information.

License

This project is licensed under the Apache-2.0 License.

Publishing

Publishing to npm is done according to these links:

版本与发布记录

@cedar-policy/authorization-for-expressjs 共发布 5 个版本,首次发布于 2025/06/17;过去 12 个月发布了 2 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.3.0latest2026/05/086 个月前
0.2.02026/03/287 个月前
0.1.22025/07/121.3 年前
0.1.12025/06/271.4 年前
0.1.02025/06/171.4 年前

关于 @cedar-policy/authorization-for-expressjs 的常见问题

@cedar-policy/authorization-for-expressjs 是什么?

Middlewares to authorize expressJS applications with Cedar

如何安装 @cedar-policy/authorization-for-expressjs?

在项目目录运行 npm install @cedar-policy/authorization-for-expressjs,或使用 pnpm add / yarn add / bun add。它还提供命令行工具 authorization-for-expressjs,可以用 npx authorization-for-expressjs 直接运行。

@cedar-policy/authorization-for-expressjs 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@cedar-policy/authorization-for-expressjs 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@cedar-policy/authorization-for-expressjs 可以商用吗?

@cedar-policy/authorization-for-expressjs 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@cedar-policy/authorization-for-expressjs 的下载量有多少?

根据 npm 官方下载统计,@cedar-policy/authorization-for-expressjs 在 2026/10/10 – 2026/11/08 这 30 天内被下载 10,277 次,日均约 343 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@cedar-policy/authorization-for-expressjs 还在维护吗?

最新版本 0.3.0 发布于 2026/05/08(6 个月前);至今共发布 5 个版本,其中过去 12 个月发布了 2 个;首次发布于 2025/06/17。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。