Enable Azure Active Directory for a .Net Core 2.2 Web Application

In this article we can see how to configure Azure Active Directory for a .Net Core 2.2 Web Application.

Step 1: Create new Web Application

Create new Web Application of .Net Core 2.2 version.

image

Add Nuget Package following:

  • Microsoft.IdentityModel.Clients.ActiveDirectory

image

Step 2: Run the Application

Run the application & Copy the URL of it.

Step 3: App Registration

You can Refer this application below.

https://jeanpaul.cloud/2019/12/13/how-to-do-app-registration-for-enterprise-application/

Step 4: App User

Add a new user to the Enterprise Application.

Step 5: Modify the Configuration File

Modify the Configuration File as following:

{
   “Authentication”: {
     “ClientId”: “CLIENT ID FROM APP REG”,
     “ClientSecret”: “CLIENT SECRET FROM APP REG”,
     “Authority”: https://login.microsoftonline.com/ACTIVE DIRECTORY GUID,
     “PostLogoutRedirectUri”: “https://localhost:44372/”,
     “CallbackPath”: “/signin-oidc”,
     “ResponseType”: “code id_token”
   }
}

Leave the last 2 parameters as it the default OIDC middleware parameters.

Step 6: Replace Startup.cs

Replace Startup.cs with the following code.

(mainly the changes are in ConfigureServices() and Configure() method)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

namespace AADenableBlog
{
     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(auth =>
             {
                 auth.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                 auth.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
             })
               .AddCookie()
               .AddOpenIdConnect(opts =>
               {
                   Configuration.GetSection(“Authentication”).Bind(opts);

                  opts.Events = new OpenIdConnectEvents
                   {
                       OnAuthorizationCodeReceived = async ctx =>
                       {
                           HttpRequest request = ctx.HttpContext.Request;

                          string currentUri = UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase, request.Path);
                           var credential = new ClientCredential(ctx.Options.ClientId, ctx.Options.ClientSecret);

                          var authContext = new AuthenticationContext(ctx.Options.Authority);

                          string resource = “https://graph.microsoft.com”;
                           AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(
                               ctx.ProtocolMessage.Code, new Uri(currentUri), credential, resource);

                          ctx.HandleCodeRedemption(result.AccessToken, result.IdToken);
                       }
                   };
               });

            services.Configure<CookiePolicyOptions>(options =>
             {
                 options.CheckConsentNeeded = context => true;
                 options.MinimumSameSitePolicy = SameSiteMode.None;
             });

             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
         }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
         {
             if (env.IsDevelopment())
             {
                 app.UseDeveloperExceptionPage();
             }
             else
             {
                 app.UseExceptionHandler(“/Home/Error”);
                 app.UseHsts();
             }

            app.UseHttpsRedirection();
             app.UseStaticFiles();
             app.UseAuthentication();
             app.UseCookiePolicy();

            app.UseMvc(routes =>
             {
                 routes.MapRoute(
                     name: “default”,
                     template: “{controller=Home}/{action=Index}/{id?}”);
             });
         }
     }
}

Step 7: Modify Controller

Modify the Home Controller as following:

[Microsoft.AspNetCore.Authorization.Authorize]

public class HomeController : Controller

// This will ensure Login prompt will prompt whenever the Controller method is accessed.

Step 8: Run the Application

Run the application & It should prompt you for the Login.  Enter the Credentials.

You can see the Login prompt.

image

Enter your New User credentials and you will be redirected to the Home Screen.

Download

The source can be downloaded here.

https://azuretrendz.files.wordpress.com/2019/12/aadenableblog.zip

Summary

In this article we have seen how to configure Azure Active Directory for a .Net Core 2.2 Web Application.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s