Azure B2C Implementation In Web API And Integrated With Swagger

Hi guys, thank you for supporting my previous blog Multi-Tenancy on Single Database, and here is one more blog for B2C Implementation.
 
I am not going to explain about the Azure setup for B2C creations and configurations, please find the below link for setting up the Tenant and Configurations.
 
For AzureB2C Setup, please go through the link completely and try to create Active Directory and configurations like signup & sign in policy and domain setup etc.
 
Most of the people can directly integrate into strap class after setting up a tenant in Azure like this,
  1.  services.AddAuthentication(options =>  
  2. {  
  3.       options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;  
  4. })  
  5. .AddJwtBearer(jwtOptions =>  
  6. {  
  7.          jwtOptions.Authority = $"https://login.microsoftonline.com/tfp/{Configuration["AzureAdB2C:Domain"]}  /{Configuration["AzureAdB2C:SignUpSignInPolicyId"]}/v2.0/";  
  8.          jwtOptions.Audience = Configuration["AzureAdB2C:ClientId"];  
  9.          jwtOptions.Events = new JwtBearerEvents  
  10.    {  
  11.            OnAuthenticationFailed = AuthenticationFailed  
  12.    };  
  13. });  
Let's try something different to implement in our own way.
 
Create a sample class with get and setter properties to set configuration, before that in appsetting.json create properties with the same names,
  1. "AzureAdB2C": {  
  2. "Instance""https://login.microsoftonline.com/tfp/",  
  3. "ClientId""###########################",  
  4. "Domain""########.onmicrosoft.com",  
  5. "SignUpSignInPolicyId""B2C_#_SignInUp"  
  6. },  
 After creating json , create a class like this,
  1. public class AzureAdB2COptions  
  2. {  
  3. public string ClientId { get; set; }  
  4. public string Instance { get; set; }  
  5. public string Domain { get; set; }  
  6. public string SignUpSignInPolicyId { get; set; }  

 Configuration class is created, but we have built the Azure connection, so create an extension method for "AuthenticationBuilder", we will call this extenesion method in startup rather than calling "AddJwtBearer"
  1. public static class AzureAdServiceCollectionExtensions  
  2.   {  
  3.            public static AuthenticationBuilder AddAzureAdB2CBearer(this AuthenticationBuilder builder)  
  4.            => builder.AddAzureAdB2CBearer(_ => { });  
  5.   } 
And Create private class to set configuration to connect to Azure using  "AzureAdB2COptions", and inject "AzureAdB2COptions" class into ConfigureAzureoption
  1. private class ConfigureAzureOptions : IConfigureNamedOptions<JwtBearerOptions>  
  2. {  
  3.    
  4.  private readonly AzureAdB2COptions _azureOptions;  
  5.    
  6.  public ConfigureAzureOptions(IOptions<AzureAdB2COptions> azureOptions)  
  7.    {  
  8.          _azureOptions = azureOptions.Value;  
  9.    }  
  10.    
  11. //Here is the Configure method for framing the Azure connection using  "AzureAdB2COptions" class.  
  12.   public void Configure(string name, JwtBearerOptions options)  
  13.    {  
  14.       options.Audience = _azureOptions.ClientId;  
  15.       options.Authority = $"{_azureOptions.Instance}/{_azureOptions.Domain}/{_azureOptions.SignUpSignInPolicyId}/v2.0";  
  16.    }  
  17.   
  18.    public void Configure(JwtBearerOptions options)  
  19.    {  
  20.          Configure(Options.DefaultName, options);  
  21.    }  

After creating this ConfigureAzureOptions class you have to inject this class into extension class or it won't call, right? So here we go.
  1. public static AuthenticationBuilder AddAzureAdB2CBearer(this AuthenticationBuilder builder, Action<AzureAdB2COptions> configureOptions)  
  2. {  
  3. // we are loading configuration  
  4.      builder.Services.Configure(configureOptions);  
  5. //here we are injecting the "ConfigureAzureOptions" class  
  6.      builder.Services.AddSingleton<IConfigureOptions<JwtBearerOptions>, ConfigureAzureOptions>();  
  7.      builder.AddJwtBearer();  
  8.      return builder;  
  9. }   
After finishing this extension method implementation we have to call this extension method, as I said, in place of "AddJwtBearer
  1. services.AddAuthentication(sharedOptions =>  
  2. {  
  3.       sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;  
  4. }).AddAzureAdB2CBearer(options => Configuration.Bind("AzureAdB2C", options));   
  5.   
Also while Authorizing our request if we want to apply any filter globally we can write it like this, it works for multi-tenancy to validate id (in case they send it from API header).
  1. public class AuthorizationFilterApply: IAsyncAuthorizationFilter {  
  2.     public Task OnAuthorizationAsync(AuthorizationFilterContext context) {  
  3.         if (context.HttpContext.User.Claims != null) {  
  4.             var email = context.HttpContext.User.Claims.FirstOrDefault(c => c.Type == "emails").Value;  
  5.         } else {  
  6.             context.HttpContext.Response.StatusCode = (int) HttpStatusCode.Unauthorized;  
  7.             context.Result = new JsonResult("Unauthorized");  
  8.             return Task.FromResult < AuthorizationFilterContext > (context);  
  9.         }  
  10.         return Task.CompletedTask;  
  11.     }  
  12. }   
Once you have written Filter you have injected in startup class or else it won't execute.
  1. services.AddMvc(config =>  
  2. {  
  3.    config.Filters.Add<AuthorizationFilterApply>();  
  4. });    
To apply Authorization we have specified the attribute on all our controller methods as below,
  1. [Authorize]  
  2. [ApiVersion("1.0")]  
  3. [Produces("application/json")]  
  4. [Route("api/v{api-version:apiVersion}/[controller]")]  
  5. public class SampleController : Controller  
  6. {  

We have completed B2C implementation nice, but here we have to test the API and we have to send a token in every request. But we are not sending a token in each request, and I will tell you how to do it. 
 
Here Swagger will come into play, it will help us to set authorization globally rather than sending each request.
 
To Integrate Swagger into the Web API, please install the below package from package manager console
  1. PM > install-package Swashbuckle.AspNetCore 
and initialize:
  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApiVersionDescriptionProvider provider)  
  2.   
  3.     app.UseSwagger(); 
Once you install this package here is a small piece of code to authorization integration.
  1. services.AddSwaggerGen(options => {  
  2.     options.AddSecurityDefinition("Bearer"new ApiKeyScheme {  
  3.         In = "header",  
  4.             Description = "JWT Authorization header using the Bearer scheme.Example: \\\"Authorization: Bearer {token}\\\"\" <h4 style='color:#49cc90'>You can get your token from <a href='azureloginurl' target='_blank'>here</a></h4>",  
  5.             Name = "Authorization",  
  6.             Type = "apiKey"  
  7.     });  
  8.     options.AddSecurityRequirement(new Dictionary < string, IEnumerable < string >> {  
  9.         {  
  10.             "Bearer",  
  11.             Enumerable.Empty < string > ()  
  12.         },  
  13.     });  
  14. });  
After your run the application , it will look like this with open locks (Not Authorized).
  Azure B2C Implementation in Web API and Integrated with Swagger
So it will enable the Authorize button on the left side corner, and when you click it will display a popup like this, 
Azure B2C Implementation in Web API and Integrated with Swagger
 
If you have a token, enter the token and click authorize, and it will authorize all your API's at a single go.
 
If you don't have a token please click the "here" link and it will take you through the generating token.
 
 Azure B2C Implementation in Web API and Integrated with Swagger 
 Azure B2C Implementation in Web API and Integrated with Swagger
 
If you can compare the first image and last one, you will be amazed (just kidding). In the first image all locks are open which means it is not authorized;  and in this image the locks are locked, which  means all API's are authorized, that's it :)
 
This is how we will integrate Azure B2C in Swagger for globally authorizing all our API's instead of sending each and every request.
 
I hope you like this post, please comment in case you're looking for anything more.