ASP.NET Core

Authentication Using Facebook In ASP.NET Core 2.0

Introduction

Sometimes, we want the users to log in using their existing credentials of third-party applications such as Facebook, Twitter, Google etc. into our application. In this article, we are going to look into authentication of ASP.NET Core app using a Facebook account.

Prerequisites

  • Install .NET Core 2.0.0 or above SDK from here.
  • Install the latest version of Visual Studio 2017 Community Edition from here.

Create MVC Web Application

  • Open Visual Studio and select File >> New >> Project.
  • After selecting the project, a “New Project” dialog will open.
  • Select .NET Core inside Visual C# menu from the left panel. Then, select “ASP.NET Core Web Application” from available project types.
  • Put the name of the project as FacebookAuth and press OK.

  • After clicking on OK, a new dialog will open asking to select the project template. You can observe two drop-down menus at the top left of the template window.
  • Select “.NET Core” and “ASP.NET Core 2.0” from these dropdowns.
  • Then, select “Web application(Model-View-Controller)” template.
  • Click on Change Authentication button, a Change Authentication dialog box will open.
  • Select “Individual User Account” and click OK.
  • Now, click OK again to create our web app.

Before running the application, we need to apply migrations to our app. Navigate to Tools >> NuGet Package Manager >> Package Manager Console.
It will open the Package Manager Console. Put in Update-Database command and hit Enter. This will update the database using Entity Framework Code First Migrations.

Press F5 to run the application. You can see a Homepage, as shown below.

Note the URL from the browser address bar. In this case, the URL is http://localhost:54575/. We need this URL to configure our Facebook app which we will be doing in our next section.

Create Facebook App

  • Navigate to https://developers.facebook.com/apps/ and sign in using your Facebook account.
  • If you do not have a Facebook account, you need to create one. You cannot proceed without a Facebook account.
  • Once you have logged in, you will be redirected to a page similar to the one shown below.

Click on Create a New App button on the top right corner. It will open a Create a New App ID form similar to the one shown below.

Here, you need to furnish the details in two fields
  • Display Name: – Give an appropriate name.

Important Note: – Do not use the word “Facebook” in the display name. You will get an error (Refer to the image below).

  • Contact Email: – Give your email id. If you do not want to provide your personal email id then you can also use any dummy email id such as xyz@gmail.com.

Do keep in mind that both the fields of this form are required so you need to provide appropriate values to all of them. Once you have furnished all the details click on Create App ID button. If there is no error in the form, your Facebook app will be created successfully and you will be redirected to the application Dashboard as shown in the image below. Here you can see a list of products that you can add to your App. Click on Set Up on the Facebook Login card. Refer to the image below.

A QuickStart wizard will be launched asking you to select platform for the app. Skip this wizard and click on Facebook Login > Settings from the navigation menu on the left.

This will take you to the Client OAuth Settings page. In the Valid OAuth redirect URIs field enter the base URL of your application with /signin-facebook appended to it. For this tutorial the URL will be http://localhost:54575/signin-facebook. Click on Save Changes. Refer to the image below.

Now click on Settings > Basic on the navigation menu. You will see the App ID and App Secret values for the Facebook app we have just created. Click on show button inside App secret field to see the value. Take a note of both values as we will need them to configure Facebook authentication in our web app.

Configure Web App to use Facebook authentication

We need to store App ID and App Secret field values in our application. We will use Secret Manager tool for this purpose. The Secret Manager tool is a project tool that can be used to store secrets such as password, API Key etc. for a .NET Core project during the development process. With the Secret Manager tool, we can associate app secrets with a specific project and can share them across multiple projects.

Open our web application once again and Right-click the project in Solution Explorer and select Manage User Secrets from the context menu.

A secrets.json file will open. Put the following code in it.
{  
  "Authentication:Facebook:AppId": "Your AppId here",  
  "Authentication:Facebook:AppSecret": "Your AppSecret here"  
}

 Now open Startup.cs file and put the following code into ConfigureServices method.

services.AddAuthentication().AddFacebook(facebookOptions =>    
{    
    facebookOptions.AppId = Configuration["Authentication:Facebook:AppId"];    
    facebookOptions.AppSecret = Configuration["Authentication:Facebook:AppSecret"];    
});

In this code section we are reading App ID and App Secret from secrets.json file for the authentication purpose.

So finally, Startup.cs will look like this.
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Threading.Tasks;  
using Microsoft.AspNetCore.Builder;  
using Microsoft.AspNetCore.Identity;  
using Microsoft.EntityFrameworkCore;  
using Microsoft.AspNetCore.Hosting;  
using Microsoft.Extensions.Configuration;  
using Microsoft.Extensions.DependencyInjection;  
using FacebookAuth.Data;  
using FacebookAuth.Models;  
using FacebookAuth.Services;  
  
namespace FacebookAuth  
{  
    public class Startup  
    {  
        public Startup(IConfiguration configuration)  
        {  
            Configuration = configuration;  
        }  
  
        public IConfiguration Configuration { get; }  
  
        // This method gets called by the runtime. Use this method to add services to the container.  
        public void ConfigureServices(IServiceCollection services)  
        {  
            services.AddDbContext<ApplicationDbContext>(options =>  
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));  
  
            services.AddIdentity<ApplicationUser, IdentityRole>()  
                .AddEntityFrameworkStores<ApplicationDbContext>()  
                .AddDefaultTokenProviders();  
  
            services.AddAuthentication().AddFacebook(facebookOptions =>  
            {  
                facebookOptions.AppId = Configuration["Authentication:Facebook:AppId"];  
                facebookOptions.AppSecret = Configuration["Authentication:Facebook:AppSecret"];  
            });  
  
            // Add application services.  
            services.AddTransient<IEmailSender, EmailSender>();  
  
            services.AddMvc();  
        }  
  
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
        {  
            if (env.IsDevelopment())  
            {  
                app.UseBrowserLink();  
                app.UseDeveloperExceptionPage();  
                app.UseDatabaseErrorPage();  
            }  
            else  
            {  
                app.UseExceptionHandler("/Home/Error");  
            }  
  
            app.UseStaticFiles();  
  
            app.UseAuthentication();  
  
            app.UseMvc(routes =>  
            {  
                routes.MapRoute(  
                    name: "default",  
                    template: "{controller=Home}/{action=Index}/{id?}");  
            });  
        }  
    }  
}  

And with this, our application is ready.

Execution Demo

Launch the application and click Login on the top right corner of home page.

 

You will be redirected to http://localhost:54575/Account/Login page, where you can see the option to login using Facebook on the right side of the page.

 

 

Clicking on the  Facebook button will take you to the Facebook authorization page where you will be asked to fill in your Facebook credentials and authorize the Facebook app to use your Facebook account.

 

 

Put in your Facebook credentials and click on Login button. You will now see a confirmation page as shown below. Click on Continue as <name> button.

 

The application will take a few moments to authenticate your Facebook account and upon successful authentication with Facebook, you will be redirected to a registration page inside our application where you need to fill in an email id to tag with your account. The email id that you have used to login to Facebook will be populated in Email id field. If you want to use another mail id you can change it.

Click register, you will be redirected to home page again but this time you can also see your registered email is on top right corner.

Conclusion

We have successfully created a Facebook app and used it to authenticate our ASP.NET Core application.

You can Get the source code from Github

Please note that secrets.json file contains dummy values. Hence replace the values with the keys of your Google app before executing it.

You can also find this article at C# Corner.

Preparing for interviews !!! Read my article on C# Coding Questions For Technical Interviews

You can check my other articles on ASP .NET Core here 

See Also

Ankit Sharma

Full Stack Consultant | GDE for Angular | Microsoft MVP | Author | Speaker | Passionate Programmer

Recent Posts

Announcing A New Blazor Course

Introduction Blazor is a .NET web framework that allows us to create client-side applications using…

3 years ago

How To Solve Sudoku Using Azure Form Recognizer

Introduction In this article, we are going to create a sudoku solver with the help…

4 years ago

Going Serverless With Blazor

Introduction In this article, we will learn how to implement Azure serverless with Blazor web…

5 years ago

Announcing A Free eBook On Angular and Firebase

Introduction Angular is an open-source framework that allows us to create applications for multiple platforms…

5 years ago

Optical Character Reader Using Angular And Azure Computer Vision

Introduction In this article, we will create an optical character recognition (OCR) application using Angular…

5 years ago

Optical Character Reader Using Blazor And Computer Vision

Introduction In this article, we will create an optical character recognition (OCR) application using Blazor…

5 years ago