@txdmobile/nestjs-auth
v6.0.5
Published
Nestjs library for auth using private and public key with user roles
Downloads
66
Readme
TxD Mobile NestJS Auth
Nestjs library for auth using private and public key with user roles
Installation
$ npm install --save @nestjs/passport passport
$ npm install --save @txdmobile/nestjs-auth
Import Module
import { NestjsAuthModule } from '@txdmobile/nestjs-auth';
const config = {
publicKey: "<PUBLIC_KEY>"
}
@Module({
imports: [NestjsAuthModule.config(config)],
...
Note: NestjsAuthModule was defined with the decorator "@Global", therefore it should only be imported in the root module of the app
Use Bearer Authentication
import { Controller, Get, UseGuards } from '@nestjs/common';
import { AppService } from './app.service';
import { RolesGuard, Roles } from '@txdmobile/nestjs-auth';
import { AuthGuard } from '@nestjs/passport';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
@UseGuards(AuthGuard())
getHello(): string {
return this.appService.getHello();
}
}
Use Bearer Authentication with Roles
import { Controller, Get, UseGuards } from '@nestjs/common';
import { AppService } from './app.service';
import { RolesGuard, Roles } from '@txdmobile/nestjs-auth';
import { AuthGuard } from '@nestjs/passport';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
@Roles('admin')
@UseGuards(AuthGuard(), RolesGuard)
getHello(): string {
return this.appService.getHello();
}
}
Retrieve the user object from request
...
@Get('user')
@UseGuards(AuthGuard())
getUser(@Req() req) {
return req.user;
}
//this code returns the following json
{
"uid": "<username>",
"roles": [
"admin"
]
}