Is cookie authentication supported in nestjs swagger?

Viewed 2013

I want to include cookie authorization in my swagger docs, however I seem to be making no progress.

According to https://docs.nestjs.com/openapi/security there looks as though cookie auth is supported in nestjs-swagger.

However, according to https://swagger.io/docs/specification/authentication/cookie-authentication/ for Swagger UI and Editor, cookie auth is not supported for "try it out"

I am unsure if I am implementing cookie auth incorrectly or if it is just not supported.

Bellow is the implementation I am trying.

In the DocumentBuilder():

.addCookieAuth('authCookie')

In controller:

@ApiCookieAuth()

I've tried adding my cookie name 'authCookie' to the @ApiCookieAuth() tag. I have also tried using .addCookieAuth('authCookie', {type: 'apiKey',in: 'cookie'})

Any way I try I get a JWT token not found error. I know this does work when I use postman so I am confused as to why I am getting this issue.

2 Answers

Basically, you can just use

  SwaggerModule.setup('swagger', app, document, {
    swaggerOptions: {
      requestInterceptor: (req) => {
        req.credentials = 'include';
        return req;
      },
    },
  });

Please note, that setting cookie value manually will not have any effect on Fetch request.

It is related to swagger-client, not to NestJs

An solition for me was to use such options in the DocumentBuilder:

.addCookieAuth('authCookie', {
  type: 'http',
  in: 'Header',
  scheme: 'Bearer'
})

And such decorator in controller:

@ApiCookieAuth()

In case you need to specify the cookie name there is a securityName parameter which will specify the name of cookie in-app

.addCookieAuth(cookieName?: string, options?: SecuritySchemeObject, securityName?: string)

After You will specify a securityName You will also need to provide it to a contoller decorator:

In the DocumentBuilder:

.addCookieAuth('auth-cookie', {
  type: 'http',
  in: 'Header',
  scheme: 'Bearer'
},
'in-app-cookie-name')

In controller:

@ApiCookieAuth('in-app-cookie-name')

This solution is working only after a manual insertion the JWT into a swagger auth input. If I get it right - SwaggerUI don`t support automatically insert of the cookie fields.

link with this issue on GitHub

Related