ASP.NET MVC , Azure AD integration using open id connect

 

ASP.NET MVC , Azure AD integration using open id connect


To integrate Azure Active Directory (Azure AD) with an ASP.NET MVC application using OpenID Connect, you can follow these core steps:

 

✅ Prerequisites

·       Azure AD tenant and App Registration (client ID and tenant ID)

·       Visual Studio

·       ASP.NET MVC (.NET Framework, not .NET Core)

 

๐Ÿ”ง Step 1: Register Your App in Azure AD

1.       Go to Azure Portal

2.       Navigate to Azure Active Directory > App registrations

3.       Click New registration

a.  Name: MyMvcApp

b.       Redirect URI: https://localhost:44300/signin-oidc (or your app’s URL + /signin-oidc)

4.       Once created, note down:

a.       Application (client) ID

b.      Directory (tenant) ID

 

๐Ÿ” Step 2: Add NuGet Packages

Install these via NuGet:

Install-Package Microsoft.Owin.Security.OpenIdConnect
Install-Package Microsoft.Owin.Security.Cookies
Install-Package Microsoft.Owin.Host.SystemWeb
 

 

๐Ÿ›  Step 3: Configure OWIN Middleware

Create a file Startup.cs and configure middleware:

using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Owin;
using System.Configuration;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;

[assembly: OwinStartup(typeof(MyMvcApp.Startup))]

namespace MyMvcApp
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId = ConfigurationManager.AppSettings["ClientId"],
                Authority = $"https://login.microsoftonline.com/{ConfigurationManager.AppSettings["TenantId"]}/v2.0",
                RedirectUri = ConfigurationManager.AppSettings["RedirectUri"],
                ResponseType = OpenIdConnectResponseType.IdToken,
                Scope = "openid profile",
                TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidateIssuer = true
                },
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = context =>
                    {
                        context.HandleResponse();
                        context.Response.Redirect("/Home/Error?message=" + context.Exception.Message);
                        return Task.FromResult(0);
                    }
                }
            });
        }
    }
}
 

 

๐Ÿ“ Step 4: Update web.config with App Settings

<appSettings>
  <add key="ClientId" value="your-client-id-here" />
  <add key="TenantId" value="your-tenant-id-here" />
  <add key="RedirectUri" value="https://localhost:44300/signin-oidc" />
</appSettings>
 

 

๐Ÿ‘ค Step 5: Add Login/Logout Logic in Controller

using System.Web;
using System.Web.Mvc;
using Microsoft.Owin.Security;

public class AccountController : Controller
{
    public void SignIn()
    {
        if (!Request.IsAuthenticated)
        {
            HttpContext.GetOwinContext().Authentication.Challenge(
                new AuthenticationProperties { RedirectUri = "/" },
                OpenIdConnectAuthenticationDefaults.AuthenticationType);
        }
    }

    public void SignOut()
    {
        HttpContext.GetOwinContext().Authentication.SignOut(
            OpenIdConnectAuthenticationDefaults.AuthenticationType,
            CookieAuthenticationDefaults.AuthenticationType);
    }
}
 

 

๐Ÿ”’ Step 6: Secure Controller with [Authorize]

[Authorize]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Error(string message)
    {
        ViewBag.Message = message;
        return View();
    }
}
 

 

๐Ÿงช Step 7: Run and Test

1.       Launch the app.

2.       You should be redirected to the Azure AD login page.

3.       After login, you’re redirected to your app.

 

Would you like the .csproj setup or global.asax configuration as well?

 

Comments

Popular posts from this blog

SPFX setup & deployment

Sites.Selected | Graph API SharePoint Permission

Configure the SharePoint Online App Catalog