Implement Active Directory Login in ASP.Net MVC
- By Junaid A February-28-2023
- 229
Literature
Implementing Active Directory Login in an ASP.NET MVC application involves several steps. Here is a basic guide to get started:
Step 1: Create an ASP.NET MVC Application Create a new ASP.NET MVC application using Visual Studio.
Step 2: Install Required Packages Install the required packages via NuGet:
- System.DirectoryServices.AccountManagement
- Microsoft.Owin.Security.ActiveDirectory
Step 3: Configure the AppSettings Section in the Web.config File In the Web.config file, add the following configuration to the <appSettings> section:
csharpCopy code
<add key="ida:Tenant" value="[Your Azure AD Tenant Name]" /> <add key="ida:ClientId" value="[Your Azure AD Application ID]" /> <add key="ida:ClientSecret" value="[Your Azure AD Application Secret]" /> <add key="ida:AADInstance" value="https://login.microsoftonline.com/{0}" /> <add key="ida:Domain" value="[Your Azure AD Domain]" />
Step 4: Configure OWIN Startup Add the following code to the Startup.cs file:
csharpCopy code
using Microsoft.Owin; using Owin; using System.Configuration; using System.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens; using Microsoft.Owin.Security; using Microsoft.Owin.Security.ActiveDirectory; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.OpenIdConnect; [assembly: OwinStartup(typeof([Your Application Name].Startup))] namespace [Your Application Name] { public partial class Startup { private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"]; private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"]; private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"]; private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"]; private string authority = string.Format(aadInstance, tenant); public void Configuration(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = CookieAuthenticationDefaults.AuthenticationType, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider { OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) } }); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = clientId, Authority = authority, PostLogoutRedirectUri = postLogoutRedirectUri, Notifications = new OpenIdConnectAuthenticationNotifications { AuthenticationFailed = context => { context.HandleResponse(); context.Response.Redirect("/Error?message=" + context.Exception.Message); return Task.FromResult(0); } } }); app.UseWindowsAzureActiveDirectoryBearerAuthentication( new WindowsAzureActiveDirectoryBearerAuthenticationOptions { Tenant = tenant, TokenValidationParameters = new TokenValidationParameters { SaveSigninToken = true, ValidAudience = clientId } }); } } }
Step 5: Add Login and Logout Actions to the AccountController Add the following code to the AccountController.cs file:
csharpCopy code
using System; using System.Configuration; using System.IdentityModel.Claims; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using System.Web.Security; using Microsoft.IdentityModel.Clients.ActiveDirectory; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.OpenIdConnect; namespace [Your Application Name].Controllers { [AllowAnonymous] public class AccountController : Controller