0

i have built an API with nestjs. To use the endpoints you have to authorize yourself via Keycloak before, that all works.

Now I want to document my API with https://github.com/nestjs/swagger. For this I want the user to be able to authenticate via the Swagger frontend and then use the endpoints. This can be done via an initial log-in when calling the Swagger UI or via the "Authorize" button.

Here is my main.ts:

import { NestFactory } from '@nestjs/core'
import { AppModule } from '@root/app.module'
import { DBService } from '@middleware/db.service'
import * as fs from 'fs'
import * as path from 'path'
import { Logger } from '@nestjs/common'
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'

async function bootstrap() {
  const ssl = process.env.SSL === 'true' ? true : false
  let httpsOptions = null
  if (ssl) {
    const keyPath = process.env.SSL_KEY_PATH || ''
    const certPath = process.env.SSL_CERT_PATH || ''
    httpsOptions = {
      key: fs.readFileSync(path.join(__dirname, keyPath), 'utf8'),
      cert: fs.readFileSync(path.join(__dirname, certPath), 'utf8')
    }
  }
  const app = await NestFactory.create(AppModule, { httpsOptions })
  app.enableCors()

  // swagger
  const config = new DocumentBuilder()
    .addOAuth2(
      {
        type: 'oauth2',
        flows: {
          password: {
            tokenUrl: `${process.env.KEYCLOAK_AUTH_URL}/auth/realms/${process.env.KEYCLOAK_REALM}/protocol/openid-connect/token`,
            authorizationUrl: `${process.env.KEYCLOAK_AUTH_URL}/auth/realms/${process.env.KEYCLOAK_REALM}/protocol/openid-connect/auth`,
            scopes: {}
          }
        }
      })
    .setTitle('MyAPI')
    .setDescription('API description')
    .setVersion('0.1')
    .addTag('AM')
    .build()
  const document = SwaggerModule.createDocument(app, config)
  SwaggerModule.setup('api', app, document, {
    swaggerOptions: { // <-- I found this by chance in a question here
      oauth: {
        clientID: process.env.KEYCLOAK_CLIENT_ID,
        realm: process.env.KEYCLOAK_REALM,
        appName: 'swagger-ui'
      }
    }
  })


  const port = Number(process.env.PORT) || 3333
  const hostname = process.env.HOSTNAME || 'localhost'
  const dbService: DBService = app.get(DBService)
  dbService.enableShutdownHooks(app)
  await app.listen(port, hostname, () => {
    const address = 'http' + (ssl ? 's' : '') + '://' + hostname + ':' + port + '/'
    Logger.log('Listening at ' + address)
  });
}
bootstrap();

The documentation https://docs.nestjs.com/openapi/security doesn't really help me.

I always get the following error despite the app.enableCors(): Error

I have also tried all possible options. origin: 'https://localhost:3334' doesn't help either.

So the question is why do i get this core error and is my swagger oauth config legit or where can I find a detailed doc on this?

1 Answers1

0

If you got CORS error, please check "Web Origins" settings in your keycloak admin console Web origin config

osbkca
  • 1
  • 2