Play with Azure AD B2C Custom Policies and .Net
Tags: azureadb2c, azure, azuredevstories, netcore
Published: 2021-03-14 15:09:02

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gb7d3jrtiriuh6mkhjey.gif)

*Application owner always look for security and effective user experience. They want to only allow authorised users to access their application. In this article I will show you how you can develop .Net app and secure it using Azure AD B2C.*

***

Before I jump directly to the coding part of it, I want to introduce each components I used :

* **.Net Core:** .NET is a free and open-source, managed computer software framework for Windows, Linux, and macOS operating systems.
* **Azure AD B2C:** Azure Active Directory B2C (Azure AD B2C) is an identity management service that enables custom control of how your customers sign up, sign in, and manage their profiles when using your iOS, Android, .NET, single-page (SPA), and other applications.
* **Visual Studio:** Microsoft Visual Studio is an integrated development environment from Microsoft. It is used to develop computer programs, as well as websites, web apps, web services and mobile apps.

**Version** of Tools and Technologies used to build this application:

* Microsoft Visual Studio Community 2019
* .Net Core 5.0
* Azure AD B2C

This is all about the technical components I used. Let’s move to the implementation part of it.

**Pre-Requisites:**

* VS 2019 Installed
* Azure AD B2C Tenant Configured

**Implementation**
First, we will setup **Azure AD B2C Custom Policies**:

**Step1:** Please go through this [link](https://docs.microsoft.com/en-us/azure/active-directory-b2c/custom-policy-get-started) to configure tenant to run custom policies, if not done yet. Either you can do the configuration manually or you can use this [link](https://b2ciefsetupapp.azurewebsites.net/) to automate it. Automating will deploy the policies from Azure AD B2C [starter pack](https://github.com/Azure-Samples/active-directory-b2c-custom-policy-starterpack), which will provide Sign Up and Sign In, Password Reset and Profile Edit journeys. In this article I am going with automate process. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n09i9ti4amhvlqa58ikc.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/64amnqxxiyssty7jmepc.png)

**Step2:** Below are the details you need to fill:

* **Domain**: B2C domain (E.g.: xxx.onmicrosoft.com)
* Facebook Reference if not required check the box.
* If needed Phone Sign-In Journey check the box.
* If want to enable JavaScript to run on the B2C Page check the box.

**Step3:** Once done click on Submit button and then Sign-in with an account with admin privileges in the provided tenant.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e1i1y9bmnlwd78j357y7.png)
 
**Step4:** AzureAD will ask you to consent to the application having the ability to create objects in your tenant (applications, keys, policies)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8c01gaiupvehu7emuhg7.png)


**Step5:** Once you consent, the application will check the tenant and create objects if not exists and upload policies. Below is the report you see once application run successfully.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1ijob306qq5eym0c272j.png)

You can also check out **Audit Logs** in the Azure Portal to get the insights.

**Step6:** Now, complete the setup by clicking on the link. 1st point to give consent to **ProxyIdentityExperienceFramework** application. 2nd point to give consent to **IEF Test App** application.

Implementation of the custom policies done, if you want you can [Test the custom policy](https://docs.microsoft.com/en-us/azure/active-directory-b2c/custom-policy-get-started).

***
**.Net Core App Implementation**

**Step1:** Open Visual Studio and click on New Project.
**Step2:** Select ASP.Net Core Web Application with C# and click Next.
**Step3:** Provide the Project Name, Location and Solution Name (You can proceed with default value).
**Step4:** Select the **Target Framework** as **.Net Core 5.0**, MVC Template and Change the **Authentication** and make it **Individual User Accounts**. From the drop-down select Connect to existing store in the cloud and fill all the details which you created during Custom Policies Implementation and click ok.
**Step5:** Review and Click Create. Now you can review Solution Explorer to check all the files created.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/daulw191r18pi51ahx02.PNG)


**appsettings.json**

```JSON
{
  "AzureAdB2C": {
    "Instance": "https://identitiessolution.b2clogin.com/tfp/",
    "ClientId": "dc71ecb1-0aa7-4c4e-9a81-af7853c6488c",
    "Domain": "identitiessolution.onmicrosoft.com",
    "SignedOutCallbackPath": "/signout/B2C_1_susi",
    "SignUpSignInPolicyId": "B2C_1A_SignUpOrSignInWithPhoneOrEmail",
    "ResetPasswordPolicyId": "B2C_1A_PasswordResetEmail",
    "EditProfilePolicyId": "B2C_1A_ProfileEditPhoneEmail",
    "CallbackPath": "/signin-oidc"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}
```

**StartUp.cs** 

To Add B2C in the Solution
```C#
public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAdB2C"));
            services.AddControllersWithViews();
            services.AddRazorPages()
                 .AddMicrosoftIdentityUI();
        }
```

Packages Related to Azure AD B2C

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qe5ttf19pvz289hkqua6.PNG)

**Important!!**
Check out the app in the Azure Portal and add the [Redirect URL](https://localhost:44353/signin-oidc) if it is not present there.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4uk2gzhnkh38m3zz18tk.PNG)

**Congratulations!! You done it!!**
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/41rcl6rlu71sutgphpoo.gif)
Now its time to see your implementation. Run the app from Visual Studio and wait to get it loaded to the browser.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ebicqc18mgqr1lhjy76q.PNG)

Click on Sign-In to see the Azure AD B2C Journey.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o8cpqztzxz1skmzgwief.PNG)

***


**Application Flow**
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5dlget3yx0y84hz2vk1x.png)

**Summary**
This is where we will stop for now.
What did we actually learn?

* Creation of Azure AD B2C Tenant
* Automation to Setup tenant to run custom policies.
* .Net Core 5.0 setup to work with Azure AD B2C

Feel like you have a ton more to learn? You're right this is a big topic.

I hope you enjoy learning and follow me to learn more. 

**Github Repo Link for .Net Code**

 Click here to go to [Github Repo](https://github.com/rprohit66/Play-with-Azure-AD-B2C-Custom-Policies-and-.Net)