2

I have API application in ASP.NET Core with two controllers and with a successful setup of multiple Bearer Authentication and Swagger. Authentication works properly. I checked it with Postman.

  • ControllerOne use authSchemeOne
  • ControllerTwo use authSchemTwo

What I want to achieve is that in Swagger I want to be logged into both schemas at one moment and configure Swagger that ControllerOne uses authSchemeOne and second one another.

Right now I must be logged in first or second. Not on both at the same time (swagger uses the last one if I am logged into both). Hope that I explained it well.

Is this somehow possible to configure it in Swagger? Authentication works properly.

Swagger UI

Thank you very much!

Update: Swagger json

First controller

/// <summary>
/// FirstController
/// </summary>
[Route("api/[controller]")]
[ApiController]
[Authorize(AuthenticationSchemes = "Bearer")]
public class FirstController : ControllerBase
{
    /// <summary>
    /// Get
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public IActionResult Get()
    {
        return Ok("FirstController");
    }
}

Second controller

/// <summary>
/// SecondController
/// </summary>
[Route("api/[controller]")]
[ApiController]
[Authorize(AuthenticationSchemes = "Bearer2")]
public class SecondController : ControllerBase
{
    /// <summary>
    /// Get
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public IActionResult Get()
    {
        return Ok("SecondController");
    }
}

Startup

public void ConfigureServices(IServiceCollection services)
    {
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "Api", Version = "v1" });

            // Set the comments path for the Swagger JSON and UI.
            var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
            var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
            c.IncludeXmlComments(xmlPath);


            var bearerSecurityScheme = new OpenApiSecurityScheme
            {
                Name = "Authorization",
                Type = SecuritySchemeType.ApiKey,
                Scheme = "Bearer",
                BearerFormat = "JWT",
                In = ParameterLocation.Header,
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            };

            var patientsLikeMeSecurityScheme = new OpenApiSecurityScheme
            {
                Name = "Authorization",
                Type = SecuritySchemeType.ApiKey,
                Scheme = "Bearer",
                BearerFormat = "JWT",
                In = ParameterLocation.Header,
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer2"
                }
            };

            c.AddSecurityDefinition("Bearer", bearerSecurityScheme);
            c.AddSecurityDefinition("Bearer2", patientsLikeMeSecurityScheme);

            c.AddSecurityRequirement(new OpenApiSecurityRequirement {
                { bearerSecurityScheme, Array.Empty<string>() },
                { patientsLikeMeSecurityScheme, Array.Empty<string>() }
            });
        });

        services.AddControllers();

        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.Audience = "Audience1";
                options.RequireHttpsMetadata = false;

                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateAudience = true,
                    ValidateIssuer = false,
                    ValidateIssuerSigningKey = false,
                    ValidateTokenReplay = false,
                    ValidateActor = false,
                    ValidateLifetime = false,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(""))
                };
            })
            .AddJwtBearer("Bearer2", options =>
            {
                options.Audience = "Audience2";
                options.RequireHttpsMetadata = false;

                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateAudience = true,
                    ValidateIssuer = false,
                    ValidateIssuerSigningKey = false,
                    ValidateTokenReplay = false,
                    ValidateActor = false,
                    ValidateLifetime = false,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(""))
                };
            });
    }
T. Dominik
  • 406
  • 3
  • 13
  • Can you post your controller and authScheme configuration? And also the OpenAPI YAML/JSON file (you can [export it from Swagger UI](https://stackoverflow.com/q/48525546/113116)). – Helen Aug 14 '20 at 09:47

0 Answers0