Search…
Auth Nest Tools
This library contains a reusable module (AuthModule) with guards that can be used to protect other REST controllers and GraphQL resolvers.

Using guards

There are a couple of guards available.
  • IdsUserGuard: validates that the request has a valid JWT bearer authorization from our identity server and checks that it has a nationalId claim, representing an authenticated user. Information from the JWT can be accessed using the CurrentAuth and CurrentUser parameter decorators.
  • IdsAuthGuard: same as IdsUserGuard but does not verify the nationalId claim. Information from the JWT can be accessed using the CurrentAuth parameter decorator.
  • ScopesGuard: checks if the access token has required scopes. These can be configured using the Scopes decorator.
You should generally add IdsUserGuard and ScopesGuard to endpoints that return user resources for the authenticated user. You can use IdsAuthGuard for endpoints that need to be available for clients authenticating with client credentials.

Configuration

Import and configure the AuthModule, example:
1
@Module({
2
imports: [
3
AuthModule.register({
4
audience: 'protected_resource',
5
issuer: 'https://localhost:6001',
6
}),
Copied!
where audience is the name your resource was registered under in IdS and issuer the IdS url.

Using in REST controller

Decorate the controller with @UseGuards:
1
@UseGuards(IdsUserGuard, ScopesGuard)
2
@Controller('clients')
3
export class ClientsController {
Copied!
and individual protected methods with @Scopes:
1
@Scopes('protected_resource/read', 'protected_resource/admin')
2
@Get(':id')
3
@ApiOkResponse({ type: Client })
4
async findOne(@Param('id') id: string): Promise<Client> {
5
// ...
6
}
Copied!
If no @Scopes are applied to a method, then no access control is enforced for that method.
Information about the logged in user can be obtained by adding @CurrentUser() user: User as an input parameter to the controller method.

Using in GraphQL resolver

Decorate the resolver with @UseGuards:
1
@UseGuards(IdsUserGuard, ScopesGuard)
2
@Resolver()
3
export class UserProfileResolver {
Copied!
and individual protected methods with @Scopes:
1
@Scopes('userProfileScope')
2
@Query(() => UserProfile, { nullable: true })
3
async getUserProfile(@CurrentUser user: User) {
4
// ... user.nationalId
5
}
Copied!
If no @Scopes are applied to a method, then no access control is enforced for that method.
Information about the logged in user can be obtained by adding @CurrentUser() user: User as an input parameter to the resolver method.

Opting out of auth

If a small subsection of your controller or app has public endpoints you can explicitly opt out of auth for those sections.
Decorate the resolver or controller with @BypassAuth:
1
@BypassAuth()
2
@Controller('clients')
3
export class ClientsController {
Copied!
Last modified 5mo ago