DotNetCurry Logo

Using Auth0 in ASP.NET MVC to achieve multiple ADFS authentication in Azure

Posted by: Kunal Chandratre , on 10/7/2015, in Category Microsoft Azure
Views: 9160
Abstract: Integrate an ASP.NET MVC application with multiple Azure hosted ADFS using 3rd Party Identity Server application like Auth0

In Part 1 of our Azure with ADFS and Identity in ASP.NET MVC series, we saw that how can we leverage Azure VM IaaS to configure ADFS. In part 2 we saw integration of single ADFS into ASP.Net MVC application using WIF. In Part 3 we saw how to configure Owin Katana to have multiple ADFS integration in ASP.NET  MVC application. In Part 4 we saw how Owin Katana based ASP.NET MVC application can be hosted in Azure WebApps and Azure Cloud Service platform.

 

In this article, we will see how we can leverage 3rd party Identity Server providers to achieve multiple ADFS integration in an ASP.NET MVC application. This saves you from lot of headache and you can start immediately provided you are ready to pay some extra bucks.

This involves the following steps –

- Registration to Auth0 (a 3rd party identity service provider)

- Creating Auth0 domain

- Registering ASP.NET MVC application in Auth0 [This is a big change because in no way we will let our application know about ADFS to be authenticated against]

- Add Auth0 URL as relying party in ADFS [This is another big change where Auth0 and ADFS are forming trust with each other, instead of the application and ADFS]

- Run the application and observe the result.

Important Points

It is worth repeating that this article is in sequence to the earlier published articles. If you are following the complete series then this article is part of a series of articles that will highlight the following important scenarios –

1. Configure ADFS in Azure VM http://www.dotnetcurry.com/windows-azure/1145/active-directory-adfs-azure-virtual-machine-authentication-aspnet-mvc

2. Implementing ADFS (or WSFederation) based authentication in MVC based ASP.NET application using Windows Identity Foundation (WIF or in Developer language – specifically using System.Identity.dll)http://www.dotnetcurry.com/windows-azure/1158/using-adfs-azure-single-signon-aspnet-mvc

3. Implementing Multiple ADFS (or WSFederation) based authentication in MVC based ASP.NET application using Microsoft OWIN KATANA. http://www.dotnetcurry.com/windows-azure/1166/aspnet-mvc-multiple-adfs-owin-katana

4. Hosting asp.net MVC application integrated with multiple wsfederation to Azure WebApps (formerly Azure websites) and Azure cloud Services http://www.dotnetcurry.com/windows-azure/1178/hosting-azure-webapps-cloud-service-roles-aspnet-mvc-adfs

5. Making life simpler – use 3rd Party (Paid) Identity Server Provider Auth0 to achieve multiple WSFederation (or ADFS) authentication in ASP.NET MVC application. (Current article explains the same).

Introduction

In this article, we will highlight the procedure of using Auth0 identity server provider to integrate an ASP.NETMVC based application with Azure /on premises hosted multiple ADFS. We will keep the scope of this article limited to localhost hosting only. For Azure WebApps or Cloud Service hosting you can follow the steps mentioned in Part 4 http://www.dotnetcurry.com/windows-azure/1178/hosting-azure-webapps-cloud-service-roles-aspnet-mvc-adfs of the series.

Applicable Technology Stack

1. Valid Microsoft Azure subscription. Free trial is available here

2. VS 2013 with update 4

3. Azure SDK 2.6 and above

4. Auth0 trial version.

Problem Statement

We have two Azure VM hosted ADFS namely Antariksh.com and IndiaUniverse.com. We need to integrate an ASP.NET MVC application with both the ADFS using Auth0.

What is Auth0 and core concepts?

Auth0 is identity-as-a-service infrastructure that's built to make implementing identity very easy for developers. The best part is it works with apps or APIs running on any popular software stack, on any popular device, authenticating with any popular identity provider. An extensive list of identity providers, both enterprise (Active Directory, LDAP, etc) and social (Facebook, Google, Twitter, etc) is supported out-of-the-box.

Auth0 abstracts the identity provider’s integration with any type of application. A high level view of Auth0 is as follows –

auth0-overview1

As you can see, in the screen, Auth0 sits in between identity providers and your application. The biggest benefit is your application has to only integrate with Auth0 interfaces which is very easy and does not have to worry about individual identity providers against which authentication need to be carried out. This saves you from lot of headache of understanding the underlying identity providers, their architecture, their API’s and so on because Auth0 does that for you. Plus integration with Auth0 is so easy and straight forward that it can get you started very quickly by writing almost zero or very less amount of code. The best part is you can have more than one authentication mechanism implemented in a single application easily. Virtually anything that sends https request can integrate with Auth0.

Connection types in Auth0

  • Custom Credentials – Using this option you can have DB based authentication mechanism implemented in your application
  • Social – Google, Facebook, twitter or any OAuth2, OAuth1 providers
  • Enterprise directories (On premises and Cloud) – LDAP, Google Apps, O365, ADFS, AD, Ws-Federation
  • Password less systems – TouchID, one time code on SMS

Each of these systems in Auth0 are referred to as Connection.

The default protocol used in Auth0 and applications is Open Id Connect. For more information on Open Id refer to the link - http://openid.net/connect/

Application in Auth0

Depending on the technology you are working with, an application to be integrated with Auth0 can be referred to as either Client or Relying Party.

Every application has settings associated with them. Some important settings are –

  • Application Name – Your application will be visible in Auth0 world by this name.
  • Client ID (read only) – Your application’s unique identifier generated automatically by Auth0 itself.
  • Client Secret - This will be used to sign and validate tokens.

Rules

Rules are JavaScript code snippets and are executed as part of Auth0. If you configure any rule, then every time the rule will get executed each time user logs in. Rules enable you to implement customization to a greater level. For example, if you want an application A to be accessible only for Finance users in region India, then rules are your friend.

Audit reports

These are very detailed, elaborative reports and can give detailed insights on activity of the user. The audit logs are shown on the dashboard page of Auth0. Some important details are –

  • Password change
  • User Sign up
  • Currently logged and active users

These details can also be downloaded using Auth0 API’s for future reference and to run your own analysis tools on the data.

With this background, we will now move towards actual implementation.

Auth0 configuration

This section will explain all the steps required for setting up Auth0 for integration with two ADFS Antariksh.com and IndiaUniverse.com. The auth0 usage in application requires 3 important steps –

1. Create connections in Auth0

2. Add Auth0 as relying party in ADFS

3. Configure MVC application for Auth0

The below sections explains all the high level steps in detail.

Registering for Auth0

You can register to Auth0 by either using your Google, Microsoft, GitHub account or custom username-password combination. As an easy way, we will select a Google based authentication mechanism for registering.

auth0-registration1

This redirects you to the Google login page. Enter your Google credentials. After successful login to Google, a pop up appears asking for new domain creation in Auth0. Let’s provide the name of domain as DotNetCurry. As of today, only 2 regions are available in Auth0 domain creation option. Select the default one, which is US West.

Auth0-domaincreation1

After creating the domain at Auth0, it may ask you for selecting the Authentication type to use for your applications. You can see there is no close button available which makes it mandatory to select something. Therefore we de-selected all options because our primary aim is to use Auth0 for integration with multiple ADFS identity providers, which can be later selected from the Dashboard view.

Create Connections in Auth0 for ADFS

Now we need to make sure that Auth0 knows about our ADFS connections so that Auth0 can treat it as identity providers using Home Realm Discovery.

Home Realm Discovery, is the process of selecting the Identity Provider based on email ID of the user for authentication if multiple Identity Providers are present.

So click on Dashboard view, select “Connection” > “Enterprise” tab. All supported Enterprise connections supported on Auth0 will get listed. Out of these, click on “Create New” against ADFS connection.

auth0-createconnection1

First provide the connection name as AntarikshADFS [without any space]. As an email ID we have to specify the root domain name of the Antariksh we had given during Antariksh ADFS provisioning in Part 1 - http://www.dotnetcurry.com/windows-azure/1145/active-directory-adfs-azure-virtual-machine-authentication-aspnet-mvc . The Root domain name provided was Antarikshdomain.com. Specify the same as Auth0 Email domain. Then provide the Metadata URL of Antariksh domain as –

https://antariksh.cloudapp.net/FederationMetadata/2007-06/FederationMetadata.xml

And then click on Save. If you are admin of the domain, then after hitting on save, another confirmation will popup to continue. Click on Continue. This complete the registration of Antariksh ADFS as connection in Auth0.

auth0-createconnection2

Now if we click on “Manage” button on “Connections” tab, then Antariksh appears as a connection as shown below –

auth0-createconnection3

Click on “Create New connections” to add connections for India Universe ADFS. The values for India Universe ADFS are as follows –

auth0-createconnection4

This completes the configuration of multiple ADFS in Auth0 and enterprise connections.

Important - For ADFS connections, Auth0 uses HRD (Home Realm Discovery). This means, if you configure the email domain fabrikam.com on an ADFS connection and a user enters john@fabrikam.com in the username field, Auth0 will match this to a configured email domain and redirect the user to ADFS. As a result, if you configure multiple ADFS connections, the UI will remain the same for all users, but depending on their email address, they'll be redirected to a different ADFS. That’s the reason we have filled Email domain field in above connection registration screenshots.

Verifying the ADFS connections in Auth0

Let’s verify if the configured ADFS connections are working correct or not. From the Dashboard, open the “Connections” > “Enterprise” > “Manage”. Then click on “Try” option as shown below –

auth0-createconnection5

You will be prompted to enter a username and password. If you have clicked on Antariksh.com ADFS, put in the credentials as antarikshdomain\antarikshadmin and related password and after successful authentication, you will receive the following details:

auth0-createconnection6

Kindly perform the same verifications test for other ADFS too, if you have to confirm successful ADFS configuration as Connection in Auth0.

Add applications in Auth0

It is important to make sure that Auth0 knows about your application for which multiple ADFS based authentication needs to be implemented. To make this possible, we need to also register our application in Auth0.

Click on “API/Apps” tab. The default application will be displayed. This is added by Auth0 itself and we don’t need it.

auth0-appregistration1

Click on “Settings” tab and delete this application by clicking on Delete button present at the bottom in “Danger zone” (pun intended). After deletion, click on “Create your first API/ App”.

auth0-appregistration2

Provide the name of app as “My localhost application”. After app creation, if you click on “Connection” tab, you will observe that both of the ADFS we had added earlier are by default applied for localhost application as shown below –

auth0-appregistration3

Here we complete the bare minimum configuration required for Auth0 to ADFS and Auth0 to application registration.

Comparing setup with Auth0 and without Auth0

Let’s compare Auth0 setup with our original setup that we did in Article 2 and Article 3 of our series.

compare-auth0

As you can see in the above diagram, previously when Auth0 was not being used as an Identity Server, the web application was acting as Relying Party (RP) for ADFS which was acting as Identity Provider (IP) for web application. Therefore the two way trust was established between Web application and ADFS.

In case Auth0, from ADFS and web application perspective, Auth0 is middleware which abstracts implementation specific details for ADFS and web application. So here Auth0 plays the dual role.

1. Auth0 acts as an Identity Provider (IP) for web application (RP)

2. Auth0 acts as an Relying Party (RP) for ADFS (IP)

During authentication when user enters his email ID then based on domain name, home realm discovery takes place by Auth0 internally and user is redirected to appropriate ADFS for authentication.

 

Add Auth0 as relying party in ADFS

Adding relying party to ADFS has been explained multiple times in previous articles of this series. If you are unsure of the process, kindly refer to Article 2 and Article 3 for details. The same process needs to be followed for adding Auth0 as the relying party to ADFS. The values of Relying Party identifiers should be as shown below –

WSFederation Endpoint - https://dotnetcurry.auth0.com/login/callback

Relying party identifies - urn:auth0:dotnetcurry

If you have specified a different name for your Auth0 account then it will be as below –

WSFederation Endpoint - https://YourAuth0AccountName.auth0.com/login/callback

Relying party identifies - urn:auth0:YourAuth0AccountName

Then add the claims rules. The screenshots below depicts the identifiers to be added and rules to be configured for sending the claims to Auth0 from ADFS –

auth0-rp1

auth0-rp2

Configure ASP.NET MVC application for Auth0

If you look at the comparison diagram shown above, you will see we have configured the second part where Auth0 is acting as relying party for ADFS identity provider. Now in this section, we will cater to first point where Auth0 acts as an identity provider for web application relying party. The section below explains how to integrate Auth0 with an ASP.NET MVC application.

Open Visual Studio in administrator mode. Then click on File > New > Project. Then create an ASP.NET web application. Provide the name of project as Auth0DNC and click ok. In the template window select MVC template and make sure that “Individual Authentication” option is selected. Then click on OK to proceed ahead.

Add Auth0 Nuget package

Click on Tools > Nuget Package Manager  > Package Manager Console in your Visual Studio. This opens up Package Manager Console. Run the command Install-Package Auth0-ASPNET-Owin and press enter.

auth0-nuget1

auth0-nuget2

This adds LoginCallback.ashx file in your existing project as shown below. This file is responsible for processing the login.

auth0-nuget3

Configure callback in Auth0 Dashboard

After authenticating the user via Auth0, Auth0 will do a POST to a built in "/signin-auth0" URL on our web site. For security purposes, we have to register this URL in the Application Settings section on Auth0 Admin app. Therefore let’s identify the localhost URL of the application. To keep consistency, we are going to change the port on which our MVC application runs. Therefore open the properties of MVC web application. Select the tab “Build”. Change the port number to 1655 as shown below. If a confirmation box appears for adding virtual directory, simply click Yes to proceed ahead. The URL of callback method will be - http://localhost:1655/signin-auth0. After POST to this URL is successful, it will redirect again to "/Auth0Account/ExternalLoginCallback" (Please do not register this route on the dashboard).

auth0-nuget4

Now let’s add this callback URL to registered Auth0 application as shown below and make sure that checkmark “Use Auth0 instead of IdP to do Single Sign On” is selected. Save the changes.

auth0-nuget5

Fill in the application web.config with Auth0 details

Now to make application aware about Auth0 as Identity Provider, we need to add Client Id, Client Secret and Auth0 domain in web configuration file of our ASP.NET MVC application. This information is present in the “Settings” tab as shown in the above screenshot.

auth0-nuget6

Update Startup.Auth.cs class file with Auth0 pipeline

The background of Startup.Auth.cs class has been already explained in Part 3 http://www.dotnetcurry.com/windows-azure/1166/aspnet-mvc-multiple-adfs-owin-katana . Following section will explain the changes that need to be done to add the Auth0 pipeline to OWIN pipeline for authentication. To make the changes, simple simply remove the entire code block from Startup.Auth.cs class to make it look like the following –

namespace Auth0DNC
{
    public partial class Startup
    {
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
             //auth0 custom code will go here   
        }
    }
}

Now first we will enable the MVC application to use a cookie to store information for the signed in user. Therefore add the following code segment –

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login")
});

Then we need to use a cookie to temporarily store information about a user logging in with 3rd party login provider. Therefore add the following code segment –

app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

It’s time to configure Auth0 as middleware in the pipeline, therefore add the following code –

var provider = new Auth0.Owin.Auth0AuthenticationProvider
{
    OnReturnEndpoint = (context) =>
    {
        // xsrf validation
        if (context.Request.Query["state"] != null && context.Request.Query["state"].Contains("xsrf="))
        {
            var state = HttpUtility.ParseQueryString(context.Request.Query["state"]);
            AntiForgery.Validate(context.Request.Cookies["__RequestVerificationToken"], state["xsrf"]);
        }

        return System.Threading.Tasks.Task.FromResult(0);
    }
};
app.UseAuth0Authentication(
clientId: System.Configuration.ConfigurationManager.AppSettings["auth0:ClientId"],
clientSecret: System.Configuration.ConfigurationManager.AppSettings["auth0:ClientSecret"],
domain: System.Configuration.ConfigurationManager.AppSettings["auth0:Domain"],
provider: provider);

Auth0AuthenticationProvider is the extension method in this case. Nuget provides a simple controller (Auth0AccountController) to process the authentication response from Auth0 and you don’t need to write a single line of code. If you want to use your own controller, make sure you set the redirectPath parameter. For example, in order to use the implementation provided by Visual Studio templates, use the following: redirectPath: "/Account/ExternalLoginCallback”.

Integrate Auth0 Login page in MVC application

There are different ways of integrating Auth0 in your site. The code snippets are available on Auth0 documentation under your Auth0 domain account. Change Login.cshtml code to the following –

@using Auth0DNC.Models
@using System.Configuration;
@model LoginViewModel
@{
    ViewBag.Title = "Log in";
}

<h2>@ViewBag.Title.</h2>
<div id="root" style="width: 280px; margin: 40px auto;">
</div>
@Html.AntiForgeryToken()
<script src="https://cdn.auth0.com/js/lock-7.0.min.js"></script>
<script>
    if (!window.location.origin) {
        window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
    }

    var lock = new Auth0Lock('@ConfigurationManager.AppSettings["auth0:ClientId"]', '@ConfigurationManager.AppSettings["auth0:Domain"]');

    var xsrf = document.getElementsByName("__RequestVerificationToken")[0].value;

    lock.show({
        container: 'root'
      , callbackURL: window.location.origin + '/signin-auth0'
      , responseType: 'code'
      , authParams: {
          scope: 'openid profile',
          state: 'xsrf=' + xsrf + '&ru=' + '@ViewBag.ReturnUrl'
      }
    });
</script>

This completes the configuration and code changes on the MVC application side.

Running the application

Alright we are all set in such a short time span to test our application with multiple ADFS and Auth0. Build the application and run it. Then from the home page, click on the Login button. The Login screen of Auth0 will appear as shown below –

auth0-runapp1

As soon as we enter the credentials as - antarikshadmin@antarikshdomain.com the login screen performs the Home Realm Discovery and displays the “Single Sign On Enabled” message and caption of Login button also changes accordingly as shown below –

auth0-runapp2

Proceed ahead and log in. Then you will be redirected to actual login screen of Antariksh.com. As you can see below the browser address bar, the actual ADFS login box is presented from Auth0 domain name. After successful login, you will be logged into the application and access will be granted.

auth0-runapp3

auth0-runapp4

 

Flow diagram between Application – Auth0 - ADFS

The following diagram explains the actual authentication flow which is self-explanatory.

auth0-flow

Conclusion

In this part of Identity and Azure series, we saw that how an ASP.NET MVC application integrates with multiple azure hosted ADFS using 3rd Party Identity Server application like Auth0. As a next step, you can also host the application in either Azure Cloud Service or Azure WebApps by following the steps given in Part 4 of this series.

Similar to Auth0, you can also explore other 3rd party services such as ClearLogin, Centrify etc.

Hereby we conclude our series of Identity and Azure. Please provide your feedback/ comments. Thanks for reading!

Download the entire source code of this article (Github)

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on Google+
Further Reading - Articles You May Like!
Author
Kunal Chandratre is a Microsoft Azure MVP. He is working as Azure SME in leading software company in (Pune) India. He also works as a Freelancer with various organizations for Azure support and provides quick start trainings on Azure to corporates and individuals on weekends. He regularly blogs about his Azure experience and is a very active member in various Microsoft Communities and also participates as a ‘Speaker’ in many events. You can follow him on Twitter at: @kunalchandratre or subscribe to his blog


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!