Node.js RBAC 튜토리얼: Express에서의 역할 기반 접근 제어
이 튜토리얼은 Express로 구축된 REST API에 역할 기반 접 근 제어(RBAC)를 추가합니다. 최종적으로 세 가지 역할(admin, editor, viewer)이 다른 경로(route)에서 다른 HTTP 메서드를 허용하도록 설정되며, 규칙은 라우트 핸들러를 수정하지 않고도 변경할 수 있는 정책 파일에 존재합니다.
동일한 모델과 정책은 모든 Casbin 구현체에서 작동하므로 이 튜토리얼의 Go, Python, Java 및 Rust 버전에서도 재사용할 수 있습니다. NestJS를 사용하는 경우 NestJS RBAC을 참조하세요.
1. 설치
npm init -y
npm install express casbin
2. 모델 작성
모델은 요청의 형태와 정책과 일치(matching)되는 방식을 정의합니다. 이를 model.conf로 저장하 세요:
[request_definition]
r = sub, obj, act
[policy_definition]
p = sub, obj, act
[role_definition]
g = _, _
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = g(r.sub, p.sub) && keyMatch2(r.obj, p.obj) && regexMatch(r.act, p.act)
r = sub, obj, act: 각 요청은 사용자(sub), URL 경로(obj), HTTP 메서드(act)로 구성됩니다.g = _, _: 사용자에게 역할을 할당할 수 있습니다.g(r.sub, p.sub): 요청의 사용자는 정책 규칙에 명시된 역할을 보유해야 합니다.keyMatch2는/api/articles/:id와 같은 경로를 매칭하며,regexMatch를 사용하면 하나의 규칙으로 여러 메서드를 나열할 수 있습니다. 기타 내장 매처(matcher)는 함수 문서에서 확인하세요.
3. 정책 작성
이를 policy.csv로 저장하세요:
p, admin, /api/*, (GET)|(POST)|(PUT)|(DELETE)
p, editor, /api/articles, (GET)|(POST)
p, editor, /api/articles/:id, (GET)|(PUT)
p, viewer, /api/articles, GET
p, viewer, /api/articles/:id, GET
g, alice, admin
g, bob, editor
g, carol, viewer
p로 시작하는 줄은 역할에 경로 및 메서드 세트에 대한 접근 권한을 부여합니다. g로 시작하는 줄은 사용자에게 역할을 할당합니다.
4. 미들웨어 추가
미들웨어는 사용자, 경로 및 메서드를 인자로 enforce를 호출하며, Casbin이 거부(no)라고 응답하면 403 Forbidden으로 응답합니다.
const express = require("express");
const { newEnforcer } = require("casbin");
// authorize asks Casbin whether the current user may call this route.
function authorize(enforcer) {
return async (req, res, next) => {
// Replace this with the user from your session or JWT.
const user = req.get("X-User") || "";
try {
const allowed = await enforcer.enforce(user, req.baseUrl + req.path, req.method);
if (!allowed) {
return res.status(403).json({ error: "forbidden" });
}
next();
} catch (err) {
next(err);
}
};
}
async function main() {
const enforcer = await newEnforcer("model.conf", "policy.csv");
const app = express();
const api = express.Router();
api.get("/articles", (req, res) => res.json({ articles: [] }));
api.post("/articles", (req, res) => res.status(201).json({ created: true }));
api.put("/articles/:id", (req, res) => res.json({ updated: req.params.id }));
api.delete("/articles/:id", (req, res) => res.json({ deleted: req.params.id }));
app.use("/api", authorize(enforcer), api);
app.listen(8080, () => console.log("listening on :8080"));
}
main();
마운트된 라우터(mounted router) 내부에서 req.path에는 마운트 지점(mount point)이 포함되지 않습니다. req.baseUrl + req.path는 정책이 참조하는 전체 경로(/api/articles)를 제공합니다.
X-User 헤더는 예제를 간결하게 유지하기 위한 것입니다. Casbin은 인가(authorization)만 처리합니다. 실제 애플리케이션에서는 인증된 JWT나 세션과 같은 인증 계층(authentication layer)에서 사용자 이름을 가져와야 합니다.
5. 테스트
node server.js
curl -i -X POST -H "X-User: bob" http://localhost:8080/api/articles # 201, editors can create
curl -i -X DELETE -H "X-User: bob" http://localhost:8080/api/articles/1 # 403, editors cannot delete
curl -i -X DELETE -H "X-User: alice" http://localhost:8080/api/articles/1 # 200, admins can
curl -i -X POST -H "X-User: carol" http://localhost:8080/api/articles # 403, viewers are read-only
6. 런타임에 역할 변경
역할과 권한은 데이터이므로 서버 실행 중에 변경할 수 있습니다:
await enforcer.addRoleForUser("dave", "editor"); // dave becomes an editor
await enforcer.deleteRoleForUser("bob", "editor"); // bob is no longer an editor
await enforcer.addPolicy("editor", "/api/comments", "POST"); // editors may now post comments
const roles = await enforcer.getRolesForUser("alice"); // ["admin"]
전체 목록은 RBAC API 및 관리 API에 있습니다.
다음 단계
- 정책을 데이터베이스에 저장. Sequelize, TypeORM, Prisma, Mongoose 등을 위한 어댑터로
policy.csv를 대체하세요. API를 통해 이루어진 정책 변경 사항은 자동으로 저장됩니다. - 여러 인스턴스 실행. 하나의 인스턴스가 정책을 변경할 때 모든 인스턴스가 정책을 다시 로드하도록 워처를 사용하세요.
- UI 요소 표시 또는 숨기기. 프론트엔드 사용법에서는
casbin.js를 사용하여 사용자의 권한을 브라우저로 보내는 방법을 설명합니다. - 멀티 테넌트 애플리케이션. 도메인이 포함된 RBAC를 사용하면 사용자가 다른 테넌트(tenant)에서 다른 역할을 가질 수 있습니다.
- 속성 기반 규칙. 역할과 ABAC를 결합하여 예를 들어 "편집자는 자신의 기사만 업데이트할 수 있음"과 같은 규칙을 만들 수 있습니다. ABAC 튜토리얼에서 단계별로 구현하는 방법을 배울 수 있습니다.
- Ready-made middleware. The middleware list has plugins for Express, Koa, NestJS, Fastify, and other frameworks.
Comments are powered by giscus and GitHub Discussions. They load from giscus.app and GitHub only after you click the button below.