Page Contents

Authentication Decorator

Syntax: @authenticate(strategyName: string, options?: object) or @authenticate(metadata: AuthenticationMetadata)

Marks a controller method as needing an authenticated user. This decorator requires a strategy name as a parameter.

Here’s an example using ‘BasicStrategy’: to authenticate user in function whoAmI:

src/controllers/who-am-i.controller.ts

import {inject} from '@loopback/context';
import {securityId, SecurityBindings, UserProfile} from '@loopback/security';
import {authenticate} from '@loopback/authentication';
import {get} from '@loopback/rest';

export class WhoAmIController {
  constructor(@inject(SecurityBindings.USER) private user: UserProfile) {}

  @authenticate('BasicStrategy')
  @get('/whoami')
  whoAmI(): string {
    return this.user[securityId];
  }
}

To configure a default authentication for all methods within a class, @authenticate can also be applied at the class level. In the code below, whoAmI is protected with BasicStrategy even though there is no @authenticate is present for the method itself. The configuration is inherited from the class. The hello method does not require authentication as it’s skipped by @authenticate.skip.

@authenticate('BasicStrategy')
export class WhoAmIController {
  constructor(@inject(SecurityBindings.USER) private user: UserProfile) {}

  @get('/whoami')
  whoAmI(): string {
    return this.user[securityId];
  }

  @authenticate.skip()
  @get('/hello')
  hello(): string {
    return 'Hello';
  }
}

For more information on authentication with LoopBack, visit here.