Showing posts with label b2c directory. Show all posts
Showing posts with label b2c directory. Show all posts

Wednesday, July 27, 2022

Azure Active Directory B2C Registration and login in .Net Core Web app

 What : Azure AD B2C is the identity management service to manage external/internal user’s profile ,signup/sign in and get token to use for your application securely without doing a lot of custom development. If you are developing an app for IOS, Android ,SPA and it is customer facing where customer can register himself and use their personal email/company email/social account to sign up and sign in , the Azure AD B2C is the quick and best choice for you.

So Overall process will be-



So, without delaying let’s create Azure AD B2C authenticated app in .Net Core web app.

Just to make simplified I will cover this tutorial in 3 Parts :

Part 1: Configure Azure AD B2C and implement in .Net core web app for signup /sign in

Part 2: Customize Default Signup/Sign In pages .

Part 3:Add Attributes to User Profile other than Default &  Update user profile

Let’s start Part 1 :

Configure Azure AD B2C and implement in .Net core web app for signup /sign in

Steps :

1.      Register Azure Active Directory When you create subscription many services not registered by default. Azure AD is one of them . To register Azure Active Directory,

Go to the subscriptions-> Resource Provider(left menu) -> Search Azure Active Directory -> select and click on Register .



2.      Create B2C tenant  : For B2C AD need to create seperate tenant .

To create B2C Tenants go to home page and search Azure Active Directory B2C  in top search box and click Ok . It will redirect you to a tenant creation screen.



 

Enter the details click review & create details


Tenant creation takes almost 1 to 2 min . By the time waiting will be good choice instead of refreshing browser. You will see below message after successfully creation of Tenant . Click on link to go to B2C tenant dashboard page.



Tenant Dashboard page


3.      Register App : Next step to register an app and get client Id and configure user flow (signin/signout/singup/password reset ) .I will cover only signup ,sign in and password reset userflow.

Click on App Registration from Left menu and click New Registration. Enter the app name “webb2cexample” rest you can leave default and click Register.

4.      Authentication : Click on the Authentication ->Add a Platform ->choose Web


5.      You need to Configure web as below  

Redirect URIs : since you have not created any application then lets put some dummy url/keep blanck , later we can update this.

Check below both highlighted check box. Access token Id Token and click configure.

 


 6.      Configure User flow (in previous version it was policies)

Go to B2C tenant and click on User Flow from left menu



You will see below dashboard for user flow . Select Sign up and Sign In and recommended as below .Click on create button.


In next screen you need to setup some configuration for sign up and sign in form which will be rendered by Microsoft identity to you application .

1.      Name : It is policies name which need to defined to render form for selected properties.  

enter   singupsing

2.      Identity Provider : Unique field for user which he cannot change after registration : check the radio button

3.      Multifactor authentication : leave as it is.

4.      Conditional Access : leave as it is.

5.      User Attribute and Claim : You  need to select what you need to capture on sign up screen and what you want to return as a claim with token. Choose what you need and create.     User Attribute can be added more ,which I will take through in part 4.

 

After creation of user flow, you can see in the list. Copy this user flow name somewhere in your local .


 Similarly, you can create new User Flow for Password reset. Which I am not going to create here. For each activity like Password Change ,sign up & sign in ,edit profile you need to create flow.

Alright, I think we have done with configuration from azure side. Let’s move to visual studio and see how to implement this.

Implement Azure AD B2C Authentication in .Net Core MVC App

1.      Create Web App : Open Visual studio and create .Net Core web App(MVC) enter project name :” AzureB2CExamples”  .On next screen select Authentication type : “Microsoft Identity Type” then click create.

 


If you explore solution explorer you can see  automatically required NuGet Packages and setup configuration will be added when we select Identity type.

NuGet Packages: 



 

2.      Open appsettings.json file and replace AzureAd config as below

        {
       
          "AzureAdB2C": {
        "Instance": "<<your tenant url>>",
            "TenantId": "Tenant Id",
            "ClientId": "Client Id",
            "Domain": "Doman Name",
            "SignUpSignInPolicyId": "B2C_1_singupsing",
            "CallbackPath": "/signin-oidc" // "defaults to /signin-oidc you can replace what you want
          },
      "Logging": {
        "LogLevel": {
              "Default": "Information",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
            }
          },
          "AllowedHosts": "*"
    }

Details can be copied from

For instance, copy url from below screen



3. open Startup.cs and replace with the below code

 using Microsoft.AspNetCore.Authentication.OpenIdConnect;

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;

namespace AzureB2CExamples
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
         
            services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAdB2C"));

            services.AddControllersWithViews();
            services.AddRazorPages()
                 .AddMicrosoftIdentityUI();
             
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });
        }
    }
}

4. copy the below url which you need to enter in Redirect uris with callbackpath  defined in appsettings.json.



Go To Registered app and update url as below and save.

 

Now If you run the application you will see default created home page.



Click on Sign In it will redirects to Microsoft default Sign In Page. Which Looks like below.



Similarly, you can click on Sign up link which Redirect you to sign up page , and you can see all the user attribute whatever you chosen while creating user flow.



Note : All the redirection for sign In/Sign out handled By Microsoft.Identity.Web.UI nuget package. Which has Account controller in which all required action is defined. 

Just need to define action and controller wherever is required . you can see in _LoginPartial.cshtml.

Let’s register one user and get the user details.

Add one menu on Application home page to show user details after sign in.

·       Open _layout.cshtml and add below menu



·       Go to HomeController and add below Actions with view named “MyProfiles”

       [Authorize] // when you try to call this action, system will check your           authentication and redirect to sign in page. 

        public IActionResult MyProfiles()

        {

            return View();

        }

 

Now Home page looks like



Click on SignIn ->SignUp and register a user .Make sure you are entering valid email id because you will get verification code

Enter your email Id and click on send verification code , after receiving code enter and click on verify code. After that fill up all the below fields and click on Create button.


 



After successful registration you will be redirected to localhost Home Page with authenticated user.



 Now Let’s see added user in azure b2c tenant

Login in azure portal and go to your B2C tenant dashboard and click users from left menu


 

In user list you can see your registered user



User can be managed directly from azure portal also .

Alright let’s get the logged in user details -Go to web app and open myprofiles view and update the below code

@using System.Security.Claims

@{

    ViewData["Title"] = "MyProfiles";

}

 

<h1>MyProfiles</h1>

 

<table class="table-hover table-striped">

    <tr>

        <th> Type</th>

        <th> Value</th>

    </tr>

 

    @foreach (Claim claim in User.Claims)

    {

        <tr>

            <td>@claim.Type</td>

            <td>@claim.Value</td>

        </tr>

}

</table>

Now run your web app and click on My Profile ,you can see below output.



 

That’s It . you are done with this part. In next part will see how to change signin/signup page to make seamless user experience.

you can download all the azure samples code : https://github.com/mkumar8184/azure-sdk-services-samples

Convert Html to Pdf in azure function and save in blob container

 In this post  I am going to create an azure function ( httpTrigger ) and send html content  which will be converted into PDF and save in bl...