Page Contents

Authentication Decorator

The decorators in LoopBack 4 are no different to the standard decorators in TypeScript. They add metadata to classes, methods, properties, or parameters. They don’t actually add any functionality, only metadata.

Securing your application’s API endpoints is done by decorating controller functions with the Authentication Decorator.

The decorator’s syntax is:

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

or

@authenticate(metadata: AuthenticationMetadata)

The strategyName is the unique name of the authentication strategy.

When the options object is specified, it must be relevant to that particular strategy.

Here is an example of the decorator using a custom authentication strategy named ‘basic’ without options, for the endpoint /whoami in a controller named WhoAmIController. (We will register an existing ‘basic’ authentication strategy in later section Authentication Strategy)

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

export class WhoAmIController {
  constructor(
    // `AuthenticationBindings.CURRENT_USER` is now an alias of
    // `SecurityBindings.USER` in @loopback/security
    // ------ ADD SNIPPET ---------
    @inject(SecurityBindings.USER)
    private userProfile: UserProfile, // ------------- END OF SNIPPET -------------
  ) {}

  // ------ ADD SNIPPET ---------
  @authenticate('basic')
  @get('/whoami')
  whoAmI(): string {
    // `securityId` is Symbol to represent the security id of the user,
    // typically the user id. You can find more information of `securityId` in
    // https://loopback.io/doc/en/lb4/Security
    return this.userProfile[securityId];
  }
  // ------------- END OF SNIPPET -------------
}

An example of the decorator when options are specified looks like this:

@authenticate('basic', { /* some options for the strategy */})

After a request is successfully authenticated, the current user profile is available on the request context. You can obtain it via dependency injection by using the SecurityBindings.USER binding key.

Parameters of the @authenticate decorator can be obtained via dependency injection using the AuthenticationBindings.METADATA binding key. It returns data of type AuthenticationMetadata provided by AuthMetadataProvider. The AuthenticationStrategyProvider, discussed in a later section, makes use of AuthenticationMetadata to figure out what name you specified as a parameter in the @authenticate decorator of a specific controller endpoint.

Next topic: Authentication Action

Previous topic: Authentication Component Overview