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.

2 thoughts on “Swagger and Azure B2C”

  1. Hello,

    I have done all things that you explain here. But I get the next error in swagger.

    Auth Error{“error”:”invalid_request”,”error_description”:”AADB2C90205:+This+application+does+not+have+sufficient+permissions+against+this+web+resource+to+perform+the+operation.\r\nCorrelation+ID:+212f83ef-4630-4b29-81a1-f92823d21643\r\nTimestamp:+2023-04-23+16:29:46Z\r\n”,”state”:”U3VuIEFwciAyMyAyMDIzIDE4OjI4OjAwIEdNVCswMjAwIChob3JhIGRlIHZlcmFubyBkZSBFdXJvcGEgY2VudHJhbCk=”}

    I don´t know what is the problem. Have I to create scope in webApi or webApp in Azure portal?
    Could you help me, please?

    1. You will need to create the scope in WebApi in Azure Portal.
      First you will need to:

      • Go to the App Registration
      • Expose an API
      • Create the scope for this API

      Next you will need to:

      • Go to the App Registration
      • API permissions
      • Add Permissions
      • My APIs
      • Select the scope you just created
      • Grant Admin Consent to scope

      Make sure to have the scope name match the scope you are sending over from Swagger.

Leave a Reply

Your email address will not be published. Required fields are marked *