Branchverse
Branchverse

Reputation: 1397

Set clientId in swagger ui nestjs oauth2

The ultimate goal (which works if clientId is provided and scopes are clicked): Use Swagger UI to get the azure Auth to receive an accessToken for further requests.

Since the client_id and scopes are static I was hoping to bypass the popup and immediately trigger what happens when clicked on the Authorize button by pre setting the client_id and scopes, since I couldn't find anything there I am atleast trying to pre fill the form so the user only has to click Authorize in my organisation.

What I tried without success:

enter image description here

The Code in main.ts of nestjs:

// Swagger
const config = new DocumentBuilder()
  .setTitle('Auth Backend')
  .setDescription('Azure PoC backend')
  .setVersion('0.1')
  .addTag('auth')
  .addOAuth2({
    type: "oauth2",
    description: "description",
    name: "AzureAD",
    flows: {
      implicit: {
        scopes: { "User.Read": "Read user profile" },
        authorizationUrl: `https://login.microsoftonline.com/${process.env.TENANT_ID}/oauth2/v2.0/authorize`,
      }
    }
  }, "AzureAD")
  .build()

const document = SwaggerModule.createDocument(app, config)
SwaggerModule.setup('swagger', app, document, {initOAuth: {clientId: process.env.CLIENT_ID, clientSecret: process.env.CLIENT_SECRET}});

Upvotes: 0

Views: 3774

Answers (1)

kavya Saraboju
kavya Saraboju

Reputation: 10839

Please try by including swaggerOptions in SwaggerModule.setup which can pass swaggerOptions into swaggerUi.generateHTML

SwaggerModule.setup('api', app, document, {   customSiteTitle: 'Your API name',   swaggerOptions: {
    oauth: {
      clientId:  clientid",
      clientSecret: "clientsecret",
      realm: "your-realms",
      appName: " ",
      scopeSeparator: " ",
      scopes: ["User.Read", "profile",”offline_access”],
    …. },
    persistAuthorization: true,   }, });

For the latest versions: ( as given by @julianklumpers in Access swagger-ui after setup to initialize oauth2 -nest.js· Issue · GitHub)

SwaggerModule.setup('api', app, document, {
    customSiteTitle: 'API',
    swaggerOptions: {
      persistAuthorization: true,
      oauth2RedirectUrl: 'https://…….’,
      initOAuth: {
        ClientId,
        ClientSecret,
        scopes: ["User.Read", "profile",”offline_access”],
        appName: ‘name of the app',
      },
    },
  });

Reference: swagger-ui oauth2 · GitHub

Upvotes: 1

Related Questions