简体   繁体   中英

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:

  • swagger options initOAuth
  • DocumentBuilder.components.requestBodies

在此处输入图像描述

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}});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM