Buscar contenidos

miércoles, 23 de enero de 2019

Azure AD B2C with ASP.NET Core 2.0


https://www.codeproject.com/Articles/1244923/Azure-AD-B-C-with-ASP-NET-Core



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’:
We’ll setup a new directory:
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:
Once directory is created, we need to register our application:
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:
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:
Here, I’ll show one policy (sign-up or sign-in) as all of them are very similar. First, we’ll setup identity provider:
Next properties/attributes that user will fill during sign-up:
Next claims that will be returned to your application:
Once you’ve setup all the policies, you’ll see them under ‘All Policies’. Note that Azure has prepended them with ‘B2C_1_’:
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:
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:
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:
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 tfpclaim type, we use that to sign-out from the policy currently in use.
Run the application:
Sign-up a new user:
Then login:
You’ll be redirected to your application:
You could edit the profile too:
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:
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);
                };
            };

1 comentario:

  1. B2C website is a big e-commerce website through which the end-user directly purchases the items via online transactions. If you are also looking for B2C web development services in Delhi. Then hire ADS & URL. We are one of the best B2C web development company that has solutions for all your website related needs. You will get the premium results as we are a team of professionals that dedicatedly work to achieve your goals with our creativity. B2C web development

    ResponderEliminar