Introduction
Microsoft Entra ID (formerly Azure Active Directory) provides authentication and authorization capabilities for modern applications. Integrating Entra ID with a .NET application using OWIN (Open Web Interface for .NET) middleware allows seamless authentication using industry-standard protocols such as OpenID Connect and OAuth 2.0.
Use case
Most of the legacy applications use the .NET Framework, and the Enterprise will look to integrate the Entra ID as an Identity provider into these applications for the SSO, as part of cloud adoption. In this use case, sometimes you may not get time to modernize the legacy application, or you may prefer a phase-by-phase approach to modernize the application. In this case, you can use OWIN libraries in your .NET Framework application to integrate with Microsoft Entra ID for Single sign-on.
In this article, I will explain how to integrate Microsoft Entra ID with a .NET application using OWIN libraries.
Step 1. Register the Application in Microsoft Entra ID.
To enable authentication, you need to register your application using the Microsoft Entra ID portal.
- Go to the Microsoft Entra ID portal.
- Navigate to App registrations > New registration.
- Enter a name for your application.
- Set the Supported account types (Single Tenant or Multi-Tenant).
- Specify the Redirect URI (e.g., https://localhost:44300/signin-oidc).
- Click Register.
- Copy the Application (client) ID and Directory (tenant) ID.
Step 2. Install Required OWIN Packages.
In your .NET Framework application, install the necessary OWIN NuGet packages by running the following commands in the Package Manager Console.
Install-Package Microsoft.Owin.Security.OpenIdConnect
Install-Package Microsoft.Owin.Security.Cookies
Install-Package Microsoft.Owin.Host.SystemWeb
Step 3. Configure OWIN Middleware.
In the Startup.cs file, configure OWIN to use Microsoft Entra ID authentication.
Create a Startup.Auth.cs file under the app start folder if it does not exist and put the code below.
[assembly: OwinStartup(typeof(EntraId_Owin_Net_Framework.Startup))]
namespace EntraId_Owin_Net_Framework
{
public partial class Startup
{
private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
private static string aadInstance = EnsureTrailingSlash(ConfigurationManager.AppSettings["ida:AADInstance"]);
private static string tenantId = ConfigurationManager.AppSettings["ida:TenantId"];
private static string RedirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"];
private static string authority = aadInstance + tenantId + "/v2.0";
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
RedirectUri = RedirectUri,
Notifications = new OpenIdConnectAuthenticationNotifications()
{
SecurityTokenValidated = (context) =>
{
string name = context.AuthenticationTicket.Identity.FindFirst("preferred_username").Value;
context.AuthenticationTicket.Identity.AddClaim(new Claim(ClaimTypes.Name, name, string.Empty));
return System.Threading.Tasks.Task.FromResult(0);
}
}
});
}
private static string EnsureTrailingSlash(string value)
{
if (value == null)
{
value = string.Empty;
}
if (!value.EndsWith("/", StringComparison.Ordinal))
{
return value + "/";
}
return value;
}
}
}
Note. Don’t forget to add this attribute [assembly: OwinStartup(typeof(EntraId_Owin_Net_Framework.Startup))]
Step 4. Enable Authentication in Web.config
Ensure your Web.config has authentication mode set to None, as OWIN handles authentication.
Add below app settings, ensure replace the ClientID, RedirectUri, TenantID, and Domain.
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="ida:ClientId" value="[Your Entra ID Application Client ID]" />
<add key="ida:AADInstance" value="https://login.microsoftonline.com/" />
<add key="ida:Domain" value="[Your Domain]" />
<add key="ida:TenantId" value="[Your Tenant ID]" />
<add key="ida:RedirectUri" value="[Your App Redirect URI]" />
<add key="owin:AutomaticAppStartup" value="true" />
</appSettings>
Step 5. Create AccountController and View.
Create AccountController and add the below code to implement SignIn and SignOut Action.
public class AccountController : Controller
{
public void SignIn()
{
// Send an OpenID Connect sign-in request.
if (!Request.IsAuthenticated)
{
HttpContext.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties { RedirectUri = "/" },
OpenIdConnectAuthenticationDefaults.AuthenticationType
);
}
}
public void SignOut()
{
string callbackUrl = Url.Action(
"SignOutCallback", "Account", routeValues: null, protocol: Request.Url.Scheme
);
HttpContext.GetOwinContext().Authentication.SignOut(
new AuthenticationProperties { RedirectUri = callbackUrl },
OpenIdConnectAuthenticationDefaults.AuthenticationType,
CookieAuthenticationDefaults.AuthenticationType
);
}
public ActionResult SignOutCallback()
{
if (Request.IsAuthenticated)
{
// Redirect to home page if the user is authenticated.
return RedirectToAction("Index", "Home");
}
return View();
}
}
_LoginPartial.cshtml
@if (Request.IsAuthenticated)
{
<text>
<ul class="navbar-nav navbar-right">
<li class="navbar-text">
Hello, @User.Identity.Name!
</li>
<li>
@Html.ActionLink("Sign out", "SignOut", "Account", new { area = "" }, new { @class = "nav-link" })
</li>
</ul>
</text>
}
else
{
<ul class="navbar-nav navbar-right">
<li>
@Html.ActionLink("Sign in", "SignIn", "Account", routeValues: null, htmlAttributes: new { id = "loginLink", @class = "nav-link" })
</li>
</ul>
}
Step 6. Run and Test the Application.
- Run the application.
- Navigate to a protected route (e.g., https://localhost:44300/home).
- The app should redirect to the Microsoft Entra ID login page.
- Enter your credentials and complete authentication.
- The application should successfully authenticate and redirect back to your app.
![Login]()
Conclusion
Integrating Microsoft Entra ID Single Sign On with a .NET application using OWIN libraries provides secure authentication leveraging OpenID Connect. By following these steps, you can easily configure authentication and enhance security in your .NET applications.