nest-auth-base
v0.2.0
Published
🔑 No-boilerplate JWT auth module for your next Nest.js project
Downloads
6
Readme
Nest auth base
Customizable module for JWT username-password authentication & authorization. Create one service, put some guards and it's done
Installation
$ npm i nest-auth-base
Working simple usage
- Create your account interface, unique username and password are always required. If you want to use roles guard, you must add the
roles
property
export interface Account {
username : string,
password : string,
roles : string[],
reputation : number
}
- Create accounts service, so library will be able to manage your datasource. In this example we use just a simple array
@Injectable()
export class AccountsService extends AuthBaseAccountsService<Account> {
private readonly accounts : Account[]
createAccount(credentials: ProcessedCredentials) {
const newAccount : Account = {
username: credentials.username,
password: credentials.hashedPassword,
roles: [ 'USER' ],
reputation: 0
}
this.accounts.push(newAccount)
return newAccount
}
getAccountByUsername(username: string) {
return this.accounts.find(account => account.username === username)
}
}
- Import
AuthBaseModule
. It's global so you can just import it in app module and use guards everywhere
@Module({
imports: [
AuthBaseModule.register({
accountsService: AccountsService,
jwtSecretKey: 'YOUR_SECRET_KEY'
})
],
controllers: [ AppController ],
})
export class AppModule {}
It's strongly recommended to get your jwtSecretKey
from your enviroment variables via Nest.js config module
Now there are two endpoints available:
Accepts body in this format:
{
"username": "USERNAME",
"password": "PASSWORD"
}
Accepts body in this format:
{
"username": "USERNAME",
"password": "PASSWORD"
}
⠀
- Add guards to your whole controller or its methods
AuthGuard
checks if user is authenticated by verifying JWT token in bearer-type Authorization
header
@Controller()
export class AppController {
@Get('me')
@UseGuards(AuthGuard)
async getAccount(@CurrentAccount() account : Account) {
return account
}
}
RolesGuard
checks if user is authenticated and has one of specified roles
@Controller()
export class AppController {
@Get('me')
@AllowedRoles('ADMIN', 'DEVELOPER')
@UseGuards(RolesGuard)
async getAccount(@CurrentAccount() account : Account) {
return account
}
}
That's all. Now you have secured API
Learn more
Docs soon