Home » Blog » Swagger and Azure B2C

Swagger and Azure B2C

Using Azure B2C gave me a bit of difficulty when I was trying to use the Swagger Gen on a .Net 6 application. Hopefully this will help others who were having the same issue.

Setting up Azure B2C

To start, I setup my Azure B2C using the Microsoft Docs – https://docs.microsoft.com/en-us/azure/active-directory-b2c/tutorial-create-tenant

We will want to create and register an application for Swagger.

During the creation make sure to set the redirect URI to https://localhost:<port>/swagger/oauth2-redirect.html

Also, make sure both Access tokens and ID tokens are checked.

Creating The App

Next I created a .Net 6 application where I attempted to add MicrosoftIdentityWebApi.

When I first tried to use Swagger to make an authorized request, I was receiving an error, which I was unable to find the root cause for was System.InvalidOperationException: IDX20803: Unable to obtain configuration from: 'System.String'

Because of this I had to change the following in my Program.cs

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAdB2C"));

To this

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(jwtOptions =>
    {
        jwtOptions.Authority = $"{builder.Configuration["AzureAdB2C:Instance"]}/{builder.Configuration["AzureAdB2C:TenantId"]}/{builder.Configuration["AzureAdB2C:SignUpSignInPolicyId"]}/v2.0/";
        jwtOptions.Audience = builder.Configuration["AzureAdB2C:ClientId"];
    });

Next I added the Swagger Configuration. This tells Swagger how to authenticate, what roles to request, and how to send the token on API requests.

 builder.Services.AddSwaggerGen(o =>
{
    o.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
    {
        Type = SecuritySchemeType.OAuth2,
        Flows = new OpenApiOAuthFlows
        {
            Implicit = new OpenApiOAuthFlow
            {
                Scopes = new Dictionary<string, string>
                {
                    {
                        "https://<company>.onmicrosoft.com/<Client Id>/weather.read",
                        "Access weather"
                    },
                },
                AuthorizationUrl =
                    new Uri("https://<company>.b2clogin.com/<company>.onmicrosoft.com/<name of user flow>/oauth2/v2.0/authorize"),
                TokenUrl = new Uri("https://<company>.b2clogin.com/<company>.onmicrosoft.com/<name of user flow>/oauth2/v2.0/token")
            }
        },
        BearerFormat = "JWT",
        In = ParameterLocation.Query,
        Scheme = "bearer"
    });
    o.AddSecurityRequirement(new OpenApiSecurityRequirement() {  
        {  
            new OpenApiSecurityScheme {  
                Reference = new OpenApiReference {  
                    Type = ReferenceType.SecurityScheme,  
                    Id = "oauth2"  
                },  
                Scheme = "oauth2",  
                Name = "oauth2",  
                In = ParameterLocation.Header,
            },  
            new List <string> ()  
        }  
    });   
});

You can get the AuthorizationUrl and TokenUrl by clicking on your B2C client, going to Application Registration, and selecting endpoints.

This will open a blade that shows all the endpoints for the apps.

Lastly I configured Swagger UI.

 if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(s =>
    {
        // Add this if you want to avoid having to enter the client ID each time.
        s.OAuthClientId("<clientId>");
    });
}

Once all that was in place I was able to run the application, click the Authenticate button, log in using Azure B2C, and make an authenticated request.

Leave a Reply

Your email address will not be published.