External Auth with .NET Core

External Auth with .NET Core

When building web applications it's advantageous to delegate the authentication to an external auth provider such as Facebook, Google, Twiter etc. Web Applications built with .NET Core provide an "easy way" to achieve this delegation. I place that frase in quotes because the process even though pretty straight forward there's a few bits where you need a bit of guidance, specially if you are new to .NET Core.

In this blog post I will go through a step by step guide into how I applied an external authentication provider to a web application in .NET Core.

These days It seems common practice to provide your users with alternative sign up/login options using one of the big tech companies, this not only speeds up the onboarding process by requiring the users to fill less fields but also helps us programmers by delegating the somewhat difficult tasks that revolve around the management of user credentials and all the complexities these bring, not to mention all the legal liabilities.

In a lot of the web applications I build I typically add some sort of authentication, most recently I have been using Azure authentication, previous to that I was using ASP.Net Identity, Regardless of the approach I consider this an important step in bulding any complex web application where user authentication is involved.

Prerequisites

In this demo I will initially be using facebook as the external authentication provider, so it would be good if you already have an existing facebook account, Also since we will be storing the user account information we will need a persistant data store, for this example we will be using a database in SQL Server to store this information. And of course the IDE of choice for this demo will be Visual Studio (2019 in my case)

I won't be explaining how to create a database using SQL Server, as there are plenty of other resources online where you can get this information so please keep in mind that you will need access to a db to follow along. 

Step 1 - Create a Facebook application

In order to use facebook as an external authenitcation provider we will need to first create a facebook app, this app will typically be named the same as your web application. In order to create your facebook application log in to your facebook account then go to the following URL Facebook Developers

Facebook Create App
You can also click on "My Apps" then on create app in the top menu

On create you will be prompt with a modal, fill the fields as required

Create New App Modal
Create New App Modal

Once the app is created you will be presented with the new app card, select the "facebook Login" Setup button

Facebook Login "Setup" Click to action
Facebook Login "Setup" Click to action

After this is selected you will be presented with a Quickstart wizzard which you can ignore. We can start fetching the values that we are interested in which is the new Facebook App Id and it's secret, you can get these by navigating in the left hand menu Settings/Basic copy these values as we will be using them later

Save your Facebook App Id and the Secret values
Save your Facebook App Id and the Secret values

Once we have these values, the final thing left to do is setup the Postback URL, which is the URL that facebook will use to redirect the users back to your site once the authentication has completed, you can find this by going to the Facebook Login / Settings in the left hand side menu

Under Facebook Login / Settings you can set the Valid OAuth Redirect URIs
Under Facebook Login / Settings you can set the Valid OAuth Redirect URIs

I have used the https://localhost:44396/signin-facebook as my redirect URI you can adjust yours as needed.

Step 2 - Create the .NET Core Web Application

Fire up Visual Studio 2019, create a new project make sure the project is a ASP.NET Core Web Application.

auth image 1
.NET Core Web Application

Configure your project name, with the values you see fit for your project

Configure your new project
Configure your new project

When configuring your new ASP.NET Core web application make sure you set the ASP.NET Core 3.1 and choose the Web Application (Model-View-Controler) as seen in the image below, The important bit for this demo is to specify that we are going to implement the authentication so in the right hand side click on Change as highlighted below. 

Chose that value
Chose that value

Once clicked a new Change Authentication window will appear, change the settings to Individual User Accounts and set to Store user accounts in-app.

Make sure you select these options
Make sure you select these options

We are almost there! At this stage we can pretty much hit F5 to run our sample web application, once loaded if we go to the Register page we will see our registration page, but note that the Use another service to register will appear empty as we have not configured this yet.

Registration Page with no external Auth option
Registration Page with no external Auth option

Step 3 - Configuring Facebook as an external authenication source

We can configure facebook as an external authentication source by simply updating the Startup.cs under the ConfigureServices method

Startup.cs

public void ConfigureServices(IServiceCollection services) { services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddDefaultIdentity(options => options.SignIn.RequireConfirmedAccount = true).AddEntityFrameworkStores(); services.AddControllersWithViews(); services.AddRazorPages(); //Adding Facebook Authentication here services.AddAuthentication().AddFacebook(facebookOptions => { facebookOptions.AppId = "YourFBAPId"; facebookOptions.AppSecret = "YourFBAppSecret"; }); }

Please note that sensitive information like the FB App Secret and FB App ID should be stored securely outside of your application using Secret Manger or Azure Key Vault

Step 4 - Apply pending migrations to update the database schema

In this step we will update the database scema with the application's data model, this will add the AspNet user related tables (Applying Migrations)

We can do this by simply opening Package Manager and runinng the following command: Update-Database

Or you can do it through the .NET Core CLI (relative to your application's path) and runinng the following command: dotnet ef database update

Before you run either of the commands above please make sure your web application's default database connection is pointing to your SQL Database in the appsettings.json (Again please consider placing sensitive information outside of your project files using Secret Manger or Azure Key Vault)

Database tables added
Database tables added

Lets check it out

After doing all the steps in this post we should be able to successfully authenticate ourselves using an external auth provider, in our case Facebook.

We now have the option to use Facebook to register into the website.
We now have the option to use Facebook to register into the website.

By clicking the Facebook registration option the site will redirect you to facebook to authenticate, after you accept the registration step it will redirect you back to the website.

Additional customisations

The interesting bit that I noticed when i first started messing around with this ASP.NET Core Identity features was that I couldn't customize the registration pages, for some reason they weren't present anywhere in my web project.

It turns out that Microsoft announced that these Razor UI Identity features are being shipped separately in another package Microsoft.AspNetCore.Identity.UI

The good news is that you can still include by scaffolding it as part of your web project but please note that it imposes a lot of responsibility. It’s a lot of security sensitive code to understand and maintain, you can read more about it here.

Scaffolding the Identity Features into your Website

If you wish to override the Identity related Views/code you will need to include these into your project, you can do this from within Visual Studio, just right click on your Web project and select Add->New Scaffolded Item.

Adding a new scaffolded item
Adding a new scaffolded item


This will show you a new popup Add New Scaffolded Item, select the Identity and add it.

Choose the Identiy Scaffold Item
Choose the Identiy Scaffold Item

You will then be presented with all the ASP.NET Core Idenity Views. Simply add the ones you wish to override or just select all of them.

Select an Identity layout to override
Select an Identity layout to override

After adding these you will now see them present in your web application under the /Areas/Identity/* path for your customisation pleasure.

Hope this helps.

Comments