@bvhoach2393/nest-check-uma
v1.0.1
Published
NestJS library for UMA (User Managed Access) permission checking
Downloads
25
Maintainers
Readme
@bvhoach2393/nest-check-uma
NestJS library for UMA (User Managed Access) permission checking
Description
Library nest-check-uma được sử dụng để thực hiện việc kiểm tra quyền UMA trước khi thực hiện các hành động khác trong ứng dụng NestJS. Library hỗ trợ việc kiểm tra Authorization header, lấy thông tin environment và gọi API UMA để xác thực quyền truy cập.
Features
- ✅ Decorator Pattern: Sử dụng
@UmaCheck(resource, scope)decorator để bảo vệ endpoints - ✅ Global Guard: Tự động kiểm tra UMA cho tất cả endpoints có decorator
- ✅ Authorization Header: Kiểm tra và xử lý Bearer token
- ✅ Environment Configuration: UMA_URL và UMA_REALM từ environment variables
- ✅ UMA API Integration: Gọi API UMA để kiểm tra quyền truy cập
- ✅ Error Handling: Xử lý lỗi và trả về ForbiddenException chuẩn NestJS
- ✅ Logging: Chi tiết log cho việc debug
- ✅ TypeScript Support: Interfaces và types đầy đủ
- ✅ Flexible Usage: Cả decorator và manual service injection
Installation
NPM
npm install @bvhoach2393/nest-check-umaYarn
yarn add @bvhoach2393/nest-check-umaPeer Dependencies
Library này yêu cầu các peer dependencies sau:
npm install @nestjs/common @nestjs/config @nestjs/core reflect-metadata rxjsEnvironment Variables
Trước khi sử dụng library, bạn cần cấu hình các environment variables sau:
UMA_URL=https://your-uma-server.com
UMA_REALM=your-realm-name
UMA_AUDIENCE=your-audience-nameUsage
1. Import Module
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { NestCheckUmaModule } from '@bvhoach2393/nest-check-uma';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
}),
NestCheckUmaModule,
],
})
export class AppModule {}2. Using UMA Decorator (Recommended)
The easiest way to protect your endpoints is using the @UmaCheck decorator:
import { Controller, Get } from '@nestjs/common';
import { UmaCheck } from '@bvhoach2393/nest-check-uma';
@Controller('protected')
export class ProtectedController {
@Get('users')
@UmaCheck('user-data', 'read') // resource, scope
async getUsers() {
// Logic được bảo vệ bởi UMA
// Guard sẽ tự động kiểm tra quyền trước khi vào method này
return { users: ['user1', 'user2'] };
}
@Get('admin')
@UmaCheck('admin-panel', 'write')
async adminAction() {
return { message: 'Admin action performed' };
}
@Get('public')
// Không có @UmaCheck decorator = endpoint công khai
async publicData() {
return { message: 'This is public data' };
}
}3. Manual Service Usage
Bạn cũng có thể sử dụng service trực tiếp:
import { Injectable } from '@nestjs/common';
import { NestCheckUmaService } from '@bvhoach2393/nest-check-uma';
@Injectable()
export class YourService {
constructor(private readonly umaService: NestCheckUmaService) {}
async performAction(authorizationHeader: string) {
const hasPermission = await this.umaService.hasPermission(
'resource-name',
'scope-name',
authorizationHeader
);
if (!hasPermission) {
throw new Error('Access denied');
}
// Thực hiện hành động khi có quyền
return 'Action performed successfully';
}
}4. Advanced Controller Usage
import { Controller, Get, Headers } from '@nestjs/common';
import { NestCheckUmaService, UmaCheckResponse } from '@bvhoach2393/nest-check-uma';
@Controller('advanced')
export class AdvancedController {
constructor(private readonly umaService: NestCheckUmaService) {}
@Get('manual-check')
async manualCheck(@Headers('authorization') authHeader: string) {
const checkResult: UmaCheckResponse = await this.umaService.checkUmaPermission({
resource: 'protected-data',
scope: 'read',
authorizationHeader: authHeader
});
if (!checkResult.hasAccess) {
return { error: checkResult.message };
}
return { data: 'This is protected data' };
}
}API Reference
Decorator
@UmaCheck(resource: string, scope: string)
Decorator để bảo vệ endpoints với UMA authorization.
@UmaCheck('user-data', 'read')
@Get('/users')
async getUsers() {
// Endpoint được bảo vệ
}Parameters:
resource(string): Tên tài nguyên cần kiểm tra quyềnscope(string): Phạm vi quyền (read, write, delete, etc.)
Behavior:
- Tự động kiểm tra Authorization header
- Gọi UMA API để xác thực quyền
- Throw
ForbiddenExceptionnếu không có quyền - Cho phép request tiếp tục nếu có quyền
Guard
UmaGuard
Global guard được tự động áp dụng cho tất cả endpoints có @UmaCheck decorator.
Features:
- Reflection metadata để lấy thông tin resource/scope
- Tự động inject và sử dụng NestCheckUmaService
- Standard NestJS exception handling
Service
NestCheckUmaService
Methods:
checkUmaPermission(params: UmaCheckParams): Promise
Phương thức chính để kiểm tra quyền UMA với các tham số chi tiết.
hasPermission(resource: string, scope: string, authorizationHeader?: string): Promise
Phương thức helper trả về boolean đơn giản để kiểm tra quyền.
Interfaces
UmaCheckParams
interface UmaCheckParams {
resource: string; // Tên tài nguyên cần kiểm tra
scope: string; // Phạm vi quyền (read, write, delete, etc.)
authorizationHeader?: string; // Header Authorization với Bearer token
}UmaCheckResponse
interface UmaCheckResponse {
hasAccess: boolean; // Kết quả kiểm tra quyền
message?: string; // Thông báo chi tiết
}UmaCheckMetadata
interface UmaCheckMetadata {
resource: string; // Resource từ decorator
scope: string; // Scope từ decorator
}Testing
Unit Tests
npm run testTest Coverage
npm run test:covWatch Mode
npm run test:watchUMA API Integration
Library gọi đến endpoint UMA với format:
POST {{UMA_URL}}/auth/uma-checkRequest body:
{
"realm": "{{UMA_REALM}}",
"token": "user-token-from-authorization-header",
"audience": "{{UMA_REALM}}",
"resource": "resource-name",
"scope": "scope-name"
}Response:
true // hoặc falseError Handling
Library xử lý các lỗi phổ biến:
- ❌ Authorization header không tồn tại
- ❌ UMA_URL hoặc UMA_REALM không được cấu hình
- ❌ Token không hợp lệ
- ❌ Lỗi kết nối đến UMA server
- ❌ Response không hợp lệ từ UMA API
Publishing
Build
npm run buildPublish to NPM
npm publishLicense
MIT
Author
bvhoach2393
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Support
For issues and questions, please create an issue on the GitHub repository.
