You can do that by adding addApiKey
or addBearerAuth
examples of which are described in other answers to this question.
From my side, I can add OAuth2 authentication
There are some differences in implementation between @nestjs/swagger3** and @nestjs/swagger4**
For the @nestjs/swagger3**
const options = new DocumentBuilder()
.setTitle('API')
.setDescription('API')
.setVersion('1.0')
.setSchemes('https', 'http')
.addOAuth2('implicit', AUTH_URL, TOKEN_URL)
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup(swaggerPath, app, document, {
swaggerOptions: {
oauth2RedirectUrl: REDIRECT_URL, // after successfully logging
oauth: {
clientId: CLIENT_ID,
},
},
});
The addOAuth2 also supports flows as password, application and accessCode
For the @nestjs/swagger4**
const options = new DocumentBuilder()
.setTitle('API')
.setDescription('API description')
.setVersion(version)
.addServer(host)
.addOAuth2(
{
type: 'oauth2',
flows: {
implicit: {
authorizationUrl: AUTH_URL + `?nonce=${getRandomNumber(9)}`, // nonce parameter is required and can be random, for example nonce=123456789
tokenUrl: TOKEN_URL,
scopes: SCOPES, // { profile: 'profile' }
},
},
},
'Authentication'
)
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup(swaggerPath, app, document, {
swaggerOptions: {
oauth2RedirectUrl: REDIRECT_URL, // after successfully logging
oauth: {
clientId: CLIENT_ID,
},
},
});