banner



Asp Net Core Identity Active Directory

Authenticating ASP.NET Core MVC applications with Azure Active Directory B2C - Part1

This article will discuss about implementing Authentication of ASP.Cyberspace Core MVC applications with Azure Active Directory B2C. Azure Agile Directory B2C (Azure AD B2C) is a cloud identity management solution for web and mobile apps. The service provides authentication for apps hosted in the cloud and on-premises. I couldn't find any documentation on how to use Azure Advert B2C in ASP.Internet Cadre MVC applications.

To go started kickoff you demand to create an Azure B2C tenant from Azure Portal. It is simple and straight forward.

Azure B2C Create new tenant

Once information technology is completed. You need to create an ASP.NET Core MVC application. You tin can utilize dotnet new mvc command or y'all can utilize new project option in Visual Studio. Side by side y'all demand to create an App Registration. You can do information technology from App Registrations bill of fare of Azure B2C.

Azure B2C Create new App registration

If you're using VS Code, gear up the Redirect URI as https://localhost:5001/signin-oidc and if you're using Visual Studio use the port number of your awarding assigned by Visual Studio. Next add ii nuget packages to your projection.

                          dotnet              add              package              Microsoft              .              Identity              .              Spider web              --              version              1.iv              .              0              dotnet              add              parcel              Microsoft              .              Identity              .              Web              .              UI              --              version              one.4              .              0                      

The Microsoft.Identity.Web packet includes the basic set of dependencies for authenticating with the Microsoft Identity platform. And the Microsoft.Identity.Web.UI includes UI functionality encapsulated in an area named MicrosoftIdentity.

Adjacent add together the following configuration settings in your appsettings.json file.

                          "              AzureB2C              "              :              {              "              Instance              "              :              "              https://login.microsoftonline.com/              "              ,              "              Domain              "              :              "              dotnetthoughts.onmicrosoft.com              "              ,              "              ClientId              "              :              "              99999999-9999-9999-9999-999999999999              "              ,              "              TenantId              "              :              "              common              "              ,              "              CallbackPath              "              :              "              /signin-oidc              "              }                      
  • For Domain, use the domain of your Azure AD B2C tenant.
  • For ClientId, use the Application (customer) ID from the app registration you created in your tenant.
  • Exit all other values as they are.

Next modify the ConfigureServices with the following code.

                          services              .              AddAuthentication              (              OpenIdConnectDefaults              .              AuthenticationScheme              )              .              AddMicrosoftIdentityWebApp              (              Configuration              .              GetSection              (              "AzureB2C"              ));              services              .              AddAuthorization              (              options              =>              {              options              .              FallbackPolicy              =              options              .              DefaultPolicy              ;              });              services              .              AddRazorPages              (              options              =>              {              options              .              Conventions              .              AllowAnonymousToPage              (              "/Index"              );              })              .              AddMvcOptions              (              options              =>              {              })              .              AddMicrosoftIdentityUI              ();                      

In a higher place the services.AddControllersWithViews(); code. And modify the Configure method and add app.UseAuthentication(); before app.UseAuthorization(); and endpoints.MapRazorPages(); in the app.UseEndpoints.

                          public              void              Configure              (              IApplicationBuilder              app              ,              IWebHostEnvironment              env              )              {              //Code omitted for brevity              app              .              UseRouting              ();              app              .              UseAuthentication              ();              app              .              UseAuthorization              ();              app              .              UseEndpoints              (              endpoints              =>              {              endpoints              .              MapControllerRoute              (              proper name              :              "default"              ,              blueprint              :              "{controller=Home}/{activity=Index}/{id?}"              );              endpoints              .              MapRazorPages              ();              });              }                      

At present you're prepare to run the application. If you run the application now information technology will automatically will be redirected to Azure AD B2C login page. Information technology may non be a expert user experience. You can set this removing the post-obit code.

                          services              .              AddAuthorization              (              options              =>              {              options              .              FallbackPolicy              =              options              .              DefaultPolicy              ;              });                      

And create a partial view with the post-obit code.

            @using System.Security.Main              <ul              class=              "navbar-nav"              >              @if (User.Identity.IsAuthenticated) {              <li              class=              "nav-item"              >              <span              class=              "navbar-text text-dark"              >Howdy @User.Identity.Name!</bridge>              </li>              <li              class=              "nav-detail"              >              <a              grade=              "nav-link text-night"              asp-area=              "MicrosoftIdentity"              asp-controller=              "Account"              asp-action=              "SignOut"              >Sign out</a>              </li>              } else {              <li              grade=              "nav-item"              >              <a              course=              "nav-link text-dark"              asp-expanse=              "MicrosoftIdentity"              asp-controller=              "Account"              asp-action=              "SignIn"              >Sign in</a>              </li>              }              </ul>                      

And modify the _Layout.cshtml file and include the partial view in the header like this.

                          <div              course=              "navbar-plummet collapse d-sm-inline-flex justify-content-between"              >              <ul              course=              "navbar-nav flex-grow-1"              >              <li              grade=              "nav-item"              >              <a              form=              "nav-link text-nighttime"              asp-expanse=              ""              asp-controller=              "Dwelling house"              asp-action=              "Index"              >Home</a>              </li>              <li              class=              "nav-item"              >              <a              form=              "nav-link text-dark"              asp-area=              ""              asp-controller=              "Home"              asp-action=              "Privacy"              >Privacy</a>              </li>              </ul>              <partial              name=              "_LoginPartial"              />              </div>                      

At present if you run the awarding you will be able to see Sign in push when y'all're launching the app and when y'all click on Sign in yous volition exist redirected to Azure B2C login page and you will be able to Sign in or Sign up. By default once you login, you will be able to see your email accost. You lot can change it to name using the post-obit lawmaking.

            services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options => {     options.TokenValidationParameters = new TokenValidationParameters     {         NameClaimType = "name",         ValidateIssuer = false     }; });          

Without the ValidateIssuer = faux configuration you will get an exception like this.

Azure B2C Create new tenant

And if y'all like to shop the information of the logged in users, you can add code like this - this lawmaking volition called one time the user logged in to the application. And in the lawmaking sample I am reading the claims and saving the information to database using DbContext.

            options.Events = new OpenIdConnectEvents() {     OnTicketReceived = async (context) =>     {         using (var scope = context.HttpContext.RequestServices.CreateScope())         {             var applicationDbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();             var objectidentifier = context.Principal                 .FindFirstValue("http://schemas.microsoft.com/identity/claims/objectidentifier");             var nameidentifier = context.Primary.FindFirstValue(ClaimTypes.NameIdentifier);             var name = context.Principal.FindFirstValue("name");             var e-mail = context.Principal.FindFirstValue("preferred_username");             var isUserExists = await applicationDbContext.ApplicationUsers                 .AnyAsync(u => u.ObjectIdentifier == objectidentifier);             if (!isUserExists)             {                 var applicationUser = new ApplicationUser()                 {                     Email = email,                     Name = name,                     ObjectIdentifier = objectidentifier,                     NameIdentifier = nameidentifier                 };                 applicationDbContext.ApplicationUsers.Add(applicationUser);                 expect applicationDbContext.SaveChangesAsync();             };         }     } };          

In this blog postal service I explained how to use Azure B2C to login to an ASP.NET Core MVC awarding and store information virtually the user to the awarding database. Azure B2C offers customized user registration and login workflow and UI customization likewise. It is called User flows. I volition explain how to create User flows and how to apply them in your ASP.NET Core MVC application.

Happy Programming :)

Asp Net Core Identity Active Directory,

Source: https://dotnetthoughts.net/azure-active-directory-b2c-in-aspnet-core-mvc-part1/

Posted by: orourkealateve.blogspot.com

0 Response to "Asp Net Core Identity Active Directory"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel