@laqus/laqus.auth.js
v1.0.9
Published
---
Downloads
447
Readme
laqus.auth.js
Uma lib criada para facilitar a implementação de autenticação e autorização em aplicações Nest.js
Features:
- AuthGuard de autenticação para ser usado globalmente
- Decorator para declarar rotas publicas
- Serviço de contexto (para recuperar as infos do usuário + correlationId)
- AuthGuard para proteger rotas de acordo com roles do keycloak
- Serviço para gerar o token da aplicação no keycloak (client session)
Instalação
Para instalar a lib no projeto:
npm i @laqus/laqus.auth.js
Adicionalmente, é necessário incluir o segmento "Keycloak" no .ENV (contatar a malawi para conseguir as variáveis de sandbox, hml e prod):
KEYCLOAK_PUBLIC_KEY=
KEYCLOAK_REALM=
KEYCLOAK_CLIENT_ID=
KEYCLOAK_CLIENT_SECRET=
KEYCLOAK_AUTH_SERVER_URL=
Para habilitar cada feature, são necessários steps diferentes:
AuthGuards
AuthGuard global
No app.module, ou no modulo base da sua app que é instanciado no main.ts, inclua o LaqusAuthGuard como provider:
providers: [
{
provide: 'APP_GUARD',
useClass: LaqusAuthGuard,
},
],
Para declarar rotas publicas, é necessario usar esse decorator:
@Controller()
export class AppController {
@Get('health')
@HttpCode(200)
@Public() // decorator para rotas publicas
healthCheck(): any {
return Math.random();
}
}
Para o swagger aceitar o novo bearer, é necessario adicionar esses trechos no main.ts e em cada controller
// main.ts
const config = new DocumentBuilder()
.setTitle('')
.setDescription('')
.setVersion('1.0')
+ .addBearerAuth(
+ {
+ type: 'http',
+ scheme: 'bearer',
+ bearerFormat: 'JWT',
+ name: 'auth',
+ description: 'Enter JWT token',
+ in: 'header',
+ },
+ 'auth',
+ )
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document);
//controller
@ApiTags('')
@Controller('')
+ @ApiBearerAuth('auth')
export class TemplateController {
constructor(
) {}
@Post()
async create() {
}
//...
Serviço de contexto e gerador de client sessions:
É necessário apenas incluir os serviços no modulo:
@Module({
imports: [FilesModule, TypeOrmModule.forFeature([MyEntity])],
controllers: [MyController],
providers: [
MyService,
MyRepository,
+ LaqusContextService,
+ LaqusKeyCloakService,
],
exports: [MyService],
})
export class MyModule {}
Authuard baseado em roles
Para usar, é necessário passar uma lista de roles:
@UseGuards(new LaqusRoleGuard(['CONSULTOR_LEITURA']))
@Get()
async findAll() {}