Click here to Skip to main content
15,886,518 members
Articles / Hosted Services / Azure

Azure AD B2C with ASP.NET Core 2.0

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
19 May 2018CPOL4 min read 10.3K   3  
How to implement Azure AD B2C authentication in ASP.NET Core 2.0. Continue reading...

This article is an entry in our Microsoft Azure IoT Contest. Articles in this section are not required to be full articles so care should be taken when voting.

Problem

How to implement Azure AD B2C authentication in ASP.NET Core 2.0.

Solution

In previous posts, we have seen how to secure our applications using:

In this post, I’ll demonstrate how to use Azure AD B2C to delegate identity and access management to Azure. One of the key differences is that we will not pre-register users in Azure AD using Azure AD domain name, like previous post, instead consumers of our applications can create users using any domain, e.g., gmail.com.

Configure Azure AD B2C

Create Azure subscription (start for free, gives you credit to play).

Create new resource and search for ‘azure active directory b2c’:

Image 1

We’ll setup a new directory:

Image 2

Enter details, including the unique ‘initial domain name’, this will become the Tenant Name that will be used in your application, e.g., below the tenant name will be fiveradb2c.onmicrosoft.com:

Image 3

Once directory is created, we need to register our application:

Image 4

Once the application is created, you’ll see ‘Application ID’ in the list. This will be used in our application later as ‘Client ID’. Make a note of this.

Click on application and ‘Properties’, enter Reply URL where Azure AD will redirect user after sign-in, sign-out, sign-up and edit profile:

Image 5

Note that these URLs are used by the middleware and match the ones shown above.

Next, we’ll setup policies for sign-in, sign-up and edit profile:

Image 6

Here, I’ll show one policy (sign-up or sign-in) as all of them are very similar. First, we’ll setup identity provider:

Image 7

Next properties/attributes that user will fill during sign-up:

Image 8

Next claims that will be returned to your application:

Image 9

Once you’ve setup all the policies, you’ll see them under ‘All Policies’. Note that Azure has prepended them with ‘B2C_1_’:

Image 10

So far you have:

  1. Created Azure AD B2C
  2. Registered your application and reply URLs
  3. Registered policies for sign-in, sign-up and profile editing

Next, we’ll setup our application and use Azure AD B2C to register and authenticate users.

Configure Application

Create an empty project and update Startup to configure services and middleware for MVC and Authentication:

C#
private readonly string TenantName = ""; // aka 'Initial Domain Name' in Azure
        private readonly string ClientId = ""; // aka 'Application Id' in Azure

        public void ConfigureServices(IServiceCollection services)
        {
            var signUpPolicy = "B2C_1_sign_up";
            var signInPolicy = "B2C_1_sign_in";
            var signUpInPolicy = "B2C_1_sign_up_in";
            var editProfilePolicy = "B2C_1_edit_profile";

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = 
                   CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme = 
                   CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = signUpInPolicy;
            })
            .AddOpenIdConnect(signUpPolicy, GetOpenIdConnectOptions(signUpPolicy))
            .AddOpenIdConnect(signInPolicy, GetOpenIdConnectOptions(signInPolicy))
            .AddOpenIdConnect(signUpInPolicy, GetOpenIdConnectOptions(signUpInPolicy))
            .AddOpenIdConnect(editProfilePolicy, 
                                  GetOpenIdConnectOptions(editProfilePolicy))
            .AddCookie();

            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseAuthentication();
            app.UseMvcWithDefaultRoute();
        }

Note that we have to add middleware to handle each policy setup on Azure AD B2C, to avoid repetition, I’ve added GetOpenIdConnectOptions method:

C#
private Action<OpenIdConnectOptions> GetOpenIdConnectOptions(string policy)
            => options =>
            {
                options.MetadataAddress = 
                   "https://login.microsoftonline.com/" + this.TenantName + 
                   "/v2.0/.well-known/openid-configuration?p=" + policy;
                options.ClientId = this.ClientId;
                options.ResponseType = OpenIdConnectResponseType.IdToken;
                options.CallbackPath = "/signin/" + policy;
                options.SignedOutCallbackPath = "/signout/" + policy;
                options.SignedOutRedirectUri = "/";
            };

Here, we are setting up Open ID Connect authentication middleware with:

  • MetadataAddress: path to the discovery endpoint to get metadata about our policy
  • ClientId: application identifier that Azure AD B2C provides for our application
  • ResponseType: value that determines authorization flow used and parameters returned from server. We are interested only in authorization token for now.
  • CallbackPath path where server will redirect after authentication. We don’t need to create this in our application, the middleware will handle this.
  • SignedOutCallbackPath: path where server will redirect after signing out.
  • SignedOutRedirectUri: path where application will redirect after signing out. This is path to our application home page, for instance

Also when configuring authentication middleware, we’ve specified sign-up or sign-in as challenge scheme. This is the middleware ASP.NET Core will use for users who have not been signed in. Azure AD B2C will present them with login page with option to sign-up too.

Once signed in, we want to store their identity in a cookie, instead of redirecting to authentication server for every request. For this reason, we’ve added cookie authentication middleware and are using that as default sign-in scheme. If the cookie is missing, users will be ‘challenged’ for their identity.

Add a controller to implement login, logout, sign-up and profile editing actions:

C#
public class SecurityController : Controller
    {
        public IActionResult Login()
        {
            return Challenge(
               new AuthenticationProperties { RedirectUri = "/" }, "B2C_1_sign_in");
        }

        [HttpPost]
        public async Task Logout()
        {
            await HttpContext.SignOutAsync(
                CookieAuthenticationDefaults.AuthenticationScheme);

            var scheme = User.FindFirst("tfp").Value;
            await HttpContext.SignOutAsync(scheme);
        }

        [Route("signup")]
        public async Task<IActionResult> SignUp()
        {
            return Challenge(
                new AuthenticationProperties { RedirectUri = "/" }, "B2C_1_sign_up");
        }

        [Route("editprofile")]
        public IActionResult EditProfile()
        {
            return Challenge(
               new AuthenticationProperties { RedirectUri = "/" }, 
               "B2C_1_edit_profile");
        }
    }

When logging out, it is important to sign-out from authentication server (Azure AD B2C) and also remove the cookie by signing out from cookie authentication scheme. Azure AD B2C sends the current profile name as tfp claim type, we use that to sign-out from the policy currently in use.

Run the application:

Image 11

Sign-up a new user:

Image 12

Then login:

Image 13

You’ll be redirected to your application:

Image 14

You could edit the profile too:

Image 15

When cancelling profile edit (or sign-up), Azure AD redirects back to your application but with an error, in order to catch that error and redirect to your home page we can handle event when setting up Open ID Connect middleware:

C#
private Action<OpenIdConnectOptions> GetOpenIdConnectOptions(string policy)
            => options =>
            {
                ...

                options.Events.OnMessageReceived = context =>
                {
                    if (!string.IsNullOrEmpty(context.ProtocolMessage.Error) &&
                          !string.IsNullOrEmpty(context.ProtocolMessage.ErrorDescription) &&                   
                           context.ProtocolMessage.ErrorDescription.StartsWith("AADB2C90091"))
                    {
                        context.Response.Redirect("/");
                        context.HandleResponse();
                    }

                    return Task.FromResult(0);
                };
            };

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
-- There are no messages in this forum --