avatarM. Ramadhan

Summary

This article provides a comprehensive guide on integrating Facebook authentication into a Blazor Server application, enabling users to log in using their Facebook accounts.

Abstract

The article is the seventeenth in a series on the Blazor Server Project and serves as a practical guide for integrating Facebook Sign-In into web applications. It outlines the steps to create a Facebook app, configure Facebook authentication middleware, store Facebook app credentials securely, and handle user sign-ins, including unregistered and registered users with varying roles. The guide emphasizes the importance of adhering to authorization specifications within the application and references previous articles for related topics such as Google authentication and role-based authorization. The tutorial is designed for developers with some experience in C#, HTML, CSS, and SQL, and it ensures that the Facebook authentication process aligns with the application's security and access control requirements.

Opinions

  • The author emphasizes the practicality of the guide, suggesting it is a hands-on resource for developers.
  • The process of integrating Facebook authentication is presented as a continuation of previous projects, implying a progressive learning approach.
  • The author acknowledges the need for compatibility with newer technologies, such as updating to .NET 7.0 for the Facebook authentication package.
  • The guide assumes familiarity with Visual Studio and development tools, indicating it is tailored for an audience with existing development skills.
  • By providing step-by-step instructions and code examples, the author aims to make the integration process straightforward and accessible for the intended audience.
  • The article encourages developers to test the application's compliance with user authorization rules, highlighting the importance of security in application development.
  • The author values reader feedback, suggesting a commitment to improving the guide based on user experiences.

Blazor Server Project #17: Facebook Authentication and Authorization

An easy guide to integrating Facebook Sign-In into your web application, allowing users to log in using their Facebook account

Table of Contents

OverviewCreate the App In FacebookInstall Facebook Authentication MiddlewareStore the Facebook app ID and secretConfigure Facebook AuthenticationSign in with FacebookUnregistered user ◃▹ Register and set the password ◃▹ AuthorizationRegistered userSummaryReferences

This article is the seventeenth in a series covering the Blazor Server Project: (1) How to create a CRUD operation using Dapper (2) Building a dropdown list involves a 1:N relationship (3) How to implement a checkbox list involving an M:N relationships (4) Understanding URL routing and navigation (5) Creating and using page layout (6) How to create a reusable modal dialog component (7) Practical guide to making a master-detail page (8) Master-detail page using dynamic query (9) How to avoid SQL injection attacks (10) Hiding/showing HTML elements (11) Migrate to ASP.NET Core 6.0 (12) Installing ASP.NET Core Identity (13) Integrating Identity tables into the existing project database (14) Authentication and authorization (15) Role-based authorization (16) How to implement Google Authentication (17) Facebook Authentication and Authorization (18) How to configure Twitter Authentication (19) How to Customize Password Policy (20) Account Lockout Policy

These articles are for anyone who wants to learn how to build Blazor Server applications in a practical approach through some sample projects. It will be straightforward if you have some experience with C#, HTML, CSS, and SQL.

Overview

In the previous article, Blazor Server Project #16, we implemented authentication using Google OAuth 2.0. For now, we cover how to apply authentication by integrating Facebook Sign-In into your web app so users can log in using their Facebook accounts. The steps are: ▸ Create the app in Facebook ▸ Install Facebook Authentication Middleware ▸ Store the Facebook Client ID and Secret ▸ Configure Facebook Authentication ▸ Sign in with Facebook

Create the App In Facebook

Figure 1 Login to Facebook
  • Log in using your Facebook account.
Figure 2 Verify the account
  • Verify your developer account by adding a mobile number
Figure 3 Review Email
  • Confirm your email.
Figure 4 Select a role
  • Select Other from the list and click Complete Registration.
Figure 5 Create App
  • Click the Create App button.
Figure 6 Select the Consumer app type
  • Select Consumer as the app type and click the Next button.
Figure 7 Add an app name
  • Type BookApp as the app name and click the Create app button.
Figure 8 Change the app name
  • The app name BookApp is not allowed. Replace with LibraryApp and click the Create app button.
Figure 9 Re-enter password
  • Re-enter your password and click Submit.
Figure 10 Add product to the app
  • Click Set Up on the Facebook Login card.
Figure 11 Select the platform
  • Select Web as the platform.
  • Click the FaceBook Login Settings in the menu on the lower left, and the following Client OAuth Settings page appears.
Figure 12 Client OAuth Settings
  • Type https://localhost:44333/signin-facebook in the text box as your development URI, click the Save changes button.
  • Click Settings > Basic in the left navigation to display the page below.
Figure 13 Basic setting
  • Click the Show button to see your App secret value. Copy App ID and secret values and paste both into a text file. It would be best if you had them now. Your App ID and secret should differ from mine in Figure 13 above.
  • You may change your email and click the Save changes button.

Install Facebook Authentication Middleware

We need to install the Microsoft.AspNetCore.Authentication.Facebook NuGet package in our project.

This project is a continuation of the Blazor Server Project #16.

If you still need to get the project, you can download it via the link below.

  • Open the project in Visual Studio 2022.
  • Select Tools > NuGet Package Manager > Manage NuGet Packages Solution… from the menu, and the NuGet Solution dialog appears.
Figure 14 NuGet package manager dialog
  • Select Browse.
  • Type facebook in the Search box
  • Click Microsoft.AspNetCore.Authentication.Facebook from the package list, check checkboxes, and select Install.
  • In the Preview Changes window, click OK to proceed with the installation and click I Accept to accept the license.
  • The following error message appears.
Figure 15 Error message

The package is not compatible with net 6.0, so update it to net 7.0 by updating Visual Studio first.

Figure 16 Update VS Community 2022
Figure 17 Progress bar of VS installation

Next, migrate to Net 7. ⦁ Deleting bin and obj folders. ⦁ Updating the target framework. ⦁ Updating installed packages.

It's similar to Blazor Server Project 11.

Reinstall the Microsoft.AspNetCore.Authentication.Facebook NuGet package.

Store the Facebook app ID and secret

  • Right-click the BookApp project in the Solution Explorer pane.
  • From the context menu, click Manage User Secrets to open the secrets.json file.
  • Please copy the following code and paste it into the file.

Listing 1 The contents of the secrets.json file

{
   "Authentication:Google:ClientId": "Your Google ClientId",
   "Authentication:Google:ClientSecret": "Your Google ClientSecret",
   "Authentication:Facebook:AppId": "<app-id>",
   "Authentication:Facebook:AppSecret": "<app-secret>"
}
  • Replace <app-id> and <app-secret> with yours.
  • Save the file. Visual Studio saves it in the file system path: %APPDATA%\Microsoft\UserSecrets\<user_secrets_id>\secrets.json

Configure Facebook Authentication

Add the following code into Startup.cs file to configure Facebook Authentication.

Listing 2 The contents of the modified Startup.cs file

...
   //Google Authentication service         
   ...
   //Facebook Authentication service
   services.AddAuthentication().AddFacebook(facebookOptions =>
   {
      facebookOptions.AppId = Configuration["Authentication:Facebook:AppId"];
      facebookOptions.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
      facebookOptions.Events = new OAuthEvents()
      {
         OnRemoteFailure = loginFailureHandler =>
         {
            var authProperties = facebookOptions.StateDataFormat.Unprotect(loginFailureHandler.Request.Query["state"]);
            loginFailureHandler.Response.Redirect("/Identity/Account/Login");
            loginFailureHandler.HandleResponse();
            return Task.FromResult(0);
         }
      };
   });
...

The application uses the AddFacebook() method to read the AppId and AppSecret from the secrets.json file.

Sign in with Facebook

The app allows any user: ⦁ an unregistered user ⦁ a registered user with no role ⦁ a registered user with one role or more to sign in.

Unregistered user

I only have one Facebook account. I unregister my account first from the app by deleting it from the AspNetUsers table.

  • From SQL Server Object Explorer, select Databases > BookDB > Tables, right-click on the AspNetUsers table and choose View Data.
Figure 18 Delete a user data

Register and set the password

Users can log in using their Facebook account even if they are not registered. For an unregistered user, the user must register and set the password after signing in.

  • Run the app, click Log in on the homepage, and follow the steps in Figure 19.
Figure 19 Sign in, register, and set the password of the unregistered user
  • Of course, like on Google Authentication, you can also register via the Register link.

Authorization

Figure 19 shows that before registering, an unregistered user can only access two menu items, Home and Books. After registering, the user can access three menu items, Home, Books, and Publishers. The user has no role and can't access the fourth menu item, Authors. The menu authorizations are compliant with the specifications in the app.

What about pages and elements authorization? Please check their compliance; see Tables 1, 2, and 3 in the previous post, Blazor Server Project #15: Role-based Authorization.

Registered user

A user can sign in as a registered user with no role, one or more. It is similar to Google authentication. See Figures 22 and 24 in the previous article, Blazor Server Project #16: How to Implement Google Authentication.

Summary

Like on Google Authentication, by integrating Facebook Sign-In into your web app, any user — unregistered users, registered users with no role, one or more — can sign in using their Facebook accounts. Their authorization is compliant with the specification in the app.

Hopefully beneficial. Your feedback will be precious.

References

Blazor
Authentication
Authorization
Facebook
Sign In
Recommended from ReadMedium