Search code examples
http-headersloopback

How do I access headers within a controller function in LoopBack?


I have a function in loopback which uses it's very own special form of authentication. I don't want to have this authentication stage done separately from the endpoint itself. I would like to do my authentication within the endpoint code.

In order to do this, I need to access the Authorization header.

How can I do this within a loopback controller function?

  @get('/item/{itemId}', {
    description: `Get a specific item`,
    responses: {}
  })
  async getItem(
    @param.path.string('itemId') itemId: string,
  ): Promise<LabResult[]> {
    // How do I get headers from here?
    const auth = somehowGetHeaders().get("Authorization");
  }

Solution

  • You can access the headers by injecting the request object. For example . . .

    @get('/item/{itemId}', {
      description: `Get a specific item`,
      responses: {}
    })
    async getItem(
      @param.path.string('itemId') itemId: string,
      @inject(RestBindings.Http.REQUEST) private req: Request
    ): Promise<LabResult[]> {
      console.log('headers', req.headers);
      // using header information here you can authenticate
    }