|
| 1 | +# Using Casbin with NestJS |
| 2 | + |
| 3 | +This guide demonstrates how to integrate Casbin with a NestJS application using a custom guard for authorization. |
| 4 | + |
| 5 | +## Installation |
| 6 | + |
| 7 | +Install Casbin in your NestJS project: |
| 8 | + |
| 9 | +```bash |
| 10 | +npm install casbin |
| 11 | +``` |
| 12 | + |
| 13 | +# Create a Casbin Guard |
| 14 | + |
| 15 | +Create a guard to handle authorization using Casbin. |
| 16 | +```bash |
| 17 | +import { |
| 18 | + Injectable, |
| 19 | + CanActivate, |
| 20 | + ExecutionContext, |
| 21 | +} from '@nestjs/common'; |
| 22 | +import { newEnforcer } from 'casbin'; |
| 23 | + |
| 24 | +@Injectable() |
| 25 | +export class CasbinGuard implements CanActivate { |
| 26 | + private enforcer: any; |
| 27 | + |
| 28 | + async onModuleInit() { |
| 29 | + this.enforcer = await newEnforcer( |
| 30 | + 'basic_model.conf', |
| 31 | + 'basic_policy.csv' |
| 32 | + ); |
| 33 | + } |
| 34 | + |
| 35 | + async canActivate(context: ExecutionContext): Promise<boolean> { |
| 36 | + const request = context.switchToHttp().getRequest(); |
| 37 | + |
| 38 | + const user = 'alice'; // example user |
| 39 | + const resource = request.url; |
| 40 | + const action = request.method; |
| 41 | + |
| 42 | + return await this.enforcer.enforce(user, resource, action); |
| 43 | + } |
| 44 | +} |
| 45 | +``` |
| 46 | +
|
| 47 | +# Use Guard in Controller |
| 48 | +
|
| 49 | +Apply the guard to protect routes. |
| 50 | +```bash |
| 51 | +import { Controller, Get, UseGuards } from '@nestjs/common'; |
| 52 | +import { CasbinGuard } from './casbin.guard'; |
| 53 | + |
| 54 | +@Controller() |
| 55 | +export class AppController { |
| 56 | + |
| 57 | + @UseGuards(CasbinGuard) |
| 58 | + @Get('data') |
| 59 | + getData() { |
| 60 | + return 'Protected Data'; |
| 61 | + } |
| 62 | +} |
| 63 | +``` |
| 64 | +
|
| 65 | +# Model Configuration |
| 66 | +
|
| 67 | +Create a file named basic_model.conf: |
| 68 | +
|
| 69 | +```bash |
| 70 | +[request_definition] |
| 71 | +r = sub, obj, act |
| 72 | + |
| 73 | +[policy_definition] |
| 74 | +p = sub, obj, act |
| 75 | + |
| 76 | +[policy_effect] |
| 77 | +e = some(where (p.eft == allow)) |
| 78 | + |
| 79 | +[matchers] |
| 80 | +m = r.sub == p.sub && r.obj == p.obj && r.act == p.act |
| 81 | +``` |
| 82 | +
|
| 83 | +# Policy Example |
| 84 | +
|
| 85 | +Create a file named basic_policy.csv: |
| 86 | +
|
| 87 | +```bash |
| 88 | +p, alice, /data, GET |
| 89 | +``` |
| 90 | +
|
| 91 | +# How It Works |
| 92 | +- Casbin loads the model and policy. |
| 93 | +- NestJS guard intercepts incoming requests. |
| 94 | +- The enforce function checks permissions. |
| 95 | +- If access is allowed, the request proceeds. |
| 96 | +- If denied, the request is blocked. |
| 97 | +
|
| 98 | +# Example Result |
| 99 | +
|
| 100 | +When accessing: |
| 101 | +```GET /data``` |
| 102 | +- User alice → Allowed |
| 103 | +- Other users → Denied |
0 commit comments