Initialize AuthZModule in AppModule
masterTo use nest-authz, you must register the AuthZModule in your AppModule. You can configure the enforcer using two methods: providing a model and policy directly, or using an enforcerProvider (the preferred method).
Configuration Options
| Option | Type | Description |
|---|---|---|
model | string | Path to the Casbin model file. |
policy | string | Path to the Casbin policy file or an adapter. |
enablePossession | boolean | Enables the use of possession (AuthPossession.(ANY|OWN|OWN_ANY)) for actions. |
userFromContext | function | REQUIRED. Accepts ExecutionContext and returns the user (string, object, or null). The AuthZGuard uses this to determine permissions. |
resourceFromContext | function | OPTIONAL. Accepts ExecutionContext and PermissionData and returns an AuthResource. Used as the default for all Permissions where resourceFromContext: true is set. |
enforcerProvider | object | Optional enforcer provider (preferred method). |
imports | Array | Optional list of imported modules required by this module. |
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [
AuthZModule.register({
model: 'model.conf',
policy: TypeORMAdapter.newAdapter({
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: 'password',
database: 'nestdb'
}),
userFromContext: (ctx) => {
const request = ctx.switchToHttp().getRequest();
return request.user && request.user.username;
},
resourceFromContext: (ctx, perm) => {
const request = ctx.switchToHttp().getRequest();
return { type: perm.resource, id: request.id };
}
}),
],
controllers: [AppController],
providers: [AppService]
})