Authentication Decorator

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

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

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

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

  1. import {inject} from '@loopback/context';
  2. import {
  3. AuthenticationBindings,
  4. UserProfile,
  5. authenticate,
  6. } from '@loopback/authentication';
  7. import {get} from '@loopback/rest';
  8. export class WhoAmIController {
  9. constructor(
  10. @inject(AuthenticationBindings.CURRENT_USER) private user: UserProfile,
  11. ) {}
  12. @authenticate('BasicStrategy')
  13. @get('/whoami')
  14. whoAmI(): string {
  15. return this.user.id;
  16. }
  17. }

Note:If only some of the controller methods are decorated with the @authenticate decorator, then the injection decorator for CURRENT_USER in the controller’s constructor must be specified as @inject(AuthenticationBindings.CURRENT_USER, {optional:true}) to avoid a binding error when an unauthenticated endpoint is accessed. Alternatively, do not inject CURRENT_USER in the controller constructor, but in the controller methods which are actually decorated with the @authenticate decorator. See Method Injection, Constructor Injection and Optional Dependencies for details.

For more information on authentication with LoopBack, visithere.