Authentication Decorator

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

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

export class WhoAmIController {
  constructor(
    @inject(AuthenticationBindings.CURRENT_USER) private user: UserProfile,
  ) {}

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

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.