Over 10 years we help companies reach their financial and branding goals. Engitech is a values-driven technology agency dedicated.

Gallery

Contacts

411 University St, Seattle, USA

engitech@oceanthemes.net

+1 -800-456-478-23

Software Development

In every web application, while making architectural and design-based decisions, deciding which identity provider is to be used is always a critical aspect because it defines overall security layer of a web app. In Microsoft technical stack, Azure AD will always have a top edge because apart from Microsoft’s top-notch security, it adds up other advantages like quick and easy SSO integrations, user & roles management, monitoring and alerts. There are various components within Azure AD, but this topic focuses on Azure AD B2C integration in .NET Core web application and custom SAML based SSO integration. So, here are the pointers which would be covered in detail:

  1. What is Azure AD
  2. Steps to setup Azure AD
  3. Integration into web application
  4. What is SAML
  5. Custom SAML Authentication in .NET web application

What is Azure AD

Microsoft introduced concept of Active Directory in 2000. In 2010, Microsoft took same concept to cloud with the name of Azure AD but with quite a lot of difference between the both. It is a cloud hosted Identity as a service solution. Azure AD acts as an authentication store and a service for managing access to various resources such as users, apps and other servers.

Basic solution architecture of any web app integrated with Azure AD looks like:

Terminology

Before starting with other concepts, it is incredibly important to understand some of the primary terminologies:

Account – If an identity has a profile, it is an account. So, identity with data becomes an account. In Microsoft terminology and in some of the services, an account can be classified as Work or School account.

Identity – Identity is not just a user but anything that can get authenticated. It includes users with credentials, applications and server with secret key or certificates-based authentication.

Authentication – Authentication is just a mechanism to permit a resource entry into a service/app/device. It does not guarantee access to all the resources. Microsoft identity platform uses Open ID Connect for authentication.

Authorization – Once authenticated, authorization provides a layer for granting and managing access/permission to do something. It provides capabilities of classifying data access to authenticated identities. Microsoft uses OAuth protocol for authorization.

Azure Tenant – A single organisation’s dedicated space or instance. Organisation here can be a logical component within a master entity. For example, Microsoft is a physical entity which has various tenants like Office 365, Dynamics CRM, and Azure.

Single Tenant – Every dedicated azure tenant without any sharing capabilities is called a single tenant.

Multi-Tenant – Azure tenants accessing services across the organisations/tenants are called multi-tenant. For example, two independent online stores having Azure AD as their identity provider are single tenants, but they become multi-tenant as soon as they start sharing identities or services between them.

Resource Group -Azure Resources Groups are logical collections of azure resources such as virtual machines, storage accounts, virtual networks, web apps, databases. It is a container that holds related resources for an Azure solution.

SSO – Single Sign On (SSO) is a mechanism to authenticate users across the applications with single credentials. By implementing SSO, Several independent applications can grant access to single user with one user id and password. In active directory environment, it can be achieved via LDAP and on web/cloud hosted environments, it can be achieved via Open ID connect, SAML. It can be classified as Social SSO and Enterprise SSO.

SAML – Security Assertion Markup Language (SAML) is an authentication mechanism for providing Single Sign On (SSO) capabilities within enterprise applications. It is like Open ID Connect but it is always used within identity providers whereas Open ID connect is used for cloud-based apps such as web APIs, web, and mobile applications.

Advantages

Azure AD provides direct replacement for managing own accounts database. It provides inbuilt capabilities for various social SSOs like Facebook, Google, and Twitter. Some of the advantages of using Azure AD are:

  1. Since it is a cloud hosted distributed system, it provides high scalability, high performance via various data centers and its robust architecture provides continuous availability.
  2. Microsoft Azure AD has proven Security mechanisms for protecting user data and credentials.
  3. Centralized administration of users throughout geographical locations.
  4. It has various useful inbuilt components such as:
    • SSO capabilities via OpenID connect and SAML
    • Secure access via MFA
    • Application proxy for publishing on-premises remote access
    • Reporting such as Security reports, Activity reports

Azure AD Architecture

Azure AD is a geographically distributed component. Its architecture assures high scalability, high availability and high performance. For achieving all of this, it requires the following components:

  1. Extensive monitoring
  2. Automated re-routing
  3. Failover and recovery capabilities

Every scalable architecture relies upon its independent building blocks. In Azure AD data tier, these building blocks are called partitions. On a high level, following diagram depicts how components of single directory partition are delivered via geographically distributed data centers:

Azure AD data tier has various front-end services that provide read-write capabilities. The components of Azure AD architecture:

Primary replica – Primary replicas receive all the writes for the partition they belong to. Every write delivered to primary replica also goes immediately to one of the secondary replicas in a different data center. This ensures data availability in case primary replica fails for any of the reasons. There are two types of primary replicas, Active primary receives all the writes, passive gets replicated from primary and passive replica can assume the role of active primary in case of a failure.

Secondary replica – Secondary replicas are responsible for read scalability. They are distributed geographically and serve all directory reads. Data replication across the secondary replicas is done asynchronously. Secondary replicas are also participants in ensuring performance because some of the reads are classified to be delivered via a closest datacenter to the user.

High Scalability is achieved via multiple partitions. Primary replica’s data is partitioned for write scalability. Read scalability is achieved by replicating data across Secondary replicas. High Availability is achieved because traffic can be shifted to any of the data centers quickly. These data centers are independent, hence enabling de-correlated nodes. Because traffic is manageable via data centers across the geographical regions, maintenance becomes extremely easy.

Setup Azure AD

Creation of Azure AD depends entirely on business requirements. Since context of this article is to setup public web application with Azure AD, following steps are for setting up Azure AD B2C tenant, publishing web application to Azure and registering web application with Azure AD to set it up as an Identity provider.

1. Create B2C tenant

Following are the high-level steps for creating Azure AD B2C tenant.

  • Create an Azure AD B2C tenant
  • Link your tenant to your subscription
  • Switch to the directory containing your Azure AD B2C tenant

For more information and step by step guide, please visit Microsoft docs at below link:

https://docs.microsoft.com/en-us/azure/active-directory-b2c/tutorial-create-tenant

2. Create and publish web application to Azure

  • Create ASP.NET Core web application in Visual Studio
  • Publish web application to Azure by creating a new App Service

https://docs.microsoft.com/en-us/azure/app-service/app-service-web-get-started-dotnet

3. Register an application

  • Register a web application in Azure AD
  • Create a client secret

https://docs.microsoft.com/en-us/azure/active-directory-b2c/tutorial-register-applications?tabs=app-reg-ga

4. Create User Flows

A user flows provide capabilities to define user journeys, which in result, generates a policy for authorization. A user flow gives control over:

  • Account types to be used in “sign in” or “sign up”
  • User attributes to be collected
  • User attributes to be sent back in the form of claim as part of auth token
  • Ability to use custom pages

https://docs.microsoft.com/en-us/azure/active-directory-b2c/tutorial-create-user-flows

Setup .NET Core Web application

For configuring .NET core web application, Authentication schemes for both login and authorization needs to be configured. Microsoft has published a NuGet package for configuring authentication handlers.

1) Please install following NuGet pakage:

Microsoft.AspNetCore.Authentication.AzureAD.UI

2) Add OpenIdConnect authentication to Startup.cs file:

services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = signUpInPolicy;
})
.AddOpenIdConnect(signUpPolicy, options =>
{
options.MetadataAddress = $”https://Laurasia.b2clogin.com/Laurasia.onmicrosoft.com/{policy}/v2.0/.well-known/openid-configuration”;
options.ClientId = “”;
options.ResponseType = OpenIdConnectResponseType.IdToken;
options.CallbackPath = “/signin/” + signUpInPolicy;
options.SignedOutCallbackPath = “/signout/” + policy;
options.SignedOutRedirectUri = “/”;
options.TokenValidationParameters.NameClaimType = “preferred_name”;
})

3) Add SignIn Action to controller

[HttpGet(“{scheme?}”)] public IActionResult SignIn([FromRoute] string scheme)
{
var redirectUrl = Url.Content(“~/”);
return Challenge(
new AuthenticationProperties { RedirectUri = redirectUrl });
}

What is SAML

Security Assertion Markup Language (SAML) is an open standard mechanism which provides capabilities for exchanging Authentication and authorization between Identity Providers (IDP) and Service Providers (SP). SAML is primarily used in enterprise applications between two business entities to provide SSO capabilities for their users. Under-given is a high -level example of how SAML works in a typical scenario:

All the SAML tokens are validated and verified against provided metadata. Metadata can be dynamic and configured on a URL or it can be statically kept in file system.

Custom SAML Authentication in .NET web application

To add SAML capabilities in a .NET web application, a controller action to receive SAML assertion and an authentication handler to initiate SSO are required.

Steps to integrate SAML assertion capabilities

1) Add NuGet package (Sustainsys.Saml2)

2) Add Saml2 authentication handler.

.AddSaml2(options =>
{
options.SPOptions.EntityId = new EntityId(this.Configuration[“Saml:SPEntityId”]);
options.SPOptions.ReturnUrl = new Uri(this.Configuration[“Saml:SPReturnUrl”]);
options.IdentityProviders.Add(
new IdentityProvider(
new EntityId(this.Configuration[“Saml:IDPEntityId”]), options.SPOptions)
{
LoadMetadata = true
});
options.SPOptions.ServiceCertificates.Add(new X509Certificate2(this.Configuration[“Saml:CertificateFileName”]));
})

3) By default, the NuGet package (added above) adds a /Saml2/Acs which validates SAML token against the metadata and signs in application upon success via cookies.

4) Example SignIn and LoginCallback controller actions

[AllowAnonymous] [HttpGet(“InitiateSingleSignOn”)] public IActionResult InitiateSingleSignOn(string returnUrl)
{
return new ChallengeResult(
Saml2Defaults.Scheme,
new AuthenticationProperties
{
RedirectUri = Url.Action(nameof(LoginCallback), new { returnUrl })
});
}

[AllowAnonymous] [HttpGet(“InitiateSingleLogout”)] public IActionResult LogoutCallback(string returnUrl)
{
HttpContext.Session.Clear();

if (!string.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}

return this.Ok();
}

Example SAML Assertions:

Sample SAML responses can be found at: https://www.samltool.com/generic_sso_res.php

To summarize, Azure AD is actually very robust, secure and flexible identity provider. It makes setting up application’s authentication and authorization very quick and easy. SAML capabilities add another layer of flexibility to have it integrated with third-party or external SPs/IDPs.

×