How to Implement Facebook Login in ASP.NET Core

In this detailed article, we will discuss how we can integrate Facebook Login to a ASP.NET Core MVC application with an illustrating example.

Introduction

In this series of articles, we have been looking at how we can implement Social Logins in an ASP.NET Core MVC application that relies on a Cookie based authentication.

So far we have created a login module along with the necessary endpoints to have users authenticated with specific authentication providers and create users within the application for further use.

The module is ready to be integrated with any login provider with a ClientID and ClientSecret to get things running.

In this section, we shall continue with how we can integrate the created login module with Facebook login.

Users will be redirected to Facebook when they click on login and redirected back to the application to create a profile and store the created profile in the database. We shall implement this in the below steps.

How to implement Facebook Login in ASP.NET Core (.NET 6)

Any social login provider authenticating users over OAuth would require us to first create an application in their developer console to obtain a clientId and clientSecret, which we’ll use in configuring the middleware.

This is because all the popular Social Login providers are built on the OAuth2 standard.

This clientId and clientSecret helps the login provider to understand which application is requesting for the authenticated user’s profile to provide user security.

These providers also present the user with a consent screen for agreeing to exchange user’s data with the requesting application which in this case is our web application along with information about what our application would receive from the user’s profile stored in the provider.

How to generate Client ID and Secret in Facebook Developer Console

To get started, we will login to developers.facebook.com and then create an application.

Log onto https://developers.facebook.com and click on Create App.

This would open up a popup, to enter the App Name and click on Create. Once the app dashboard opens up, on the left panel, click on + icon next to Add Products and select Facebook Login.

wp-content/uploads/2022/05/create-fb-app.png

Now Facebook Login is added onto the application. Under the Facebook Login, goto settings and in the redirect Urls add https://yourdomain/user/identity-login.

wp-content/uploads/2022/05/configure-fb-login.png

We have now set up the Facebook Login. We will copy the ClientId and ClientSecret of this created application.

On the left panel, click on Settings below Dashboard, which will open up the basic settings page. On the top, you have the Application Id which is the Client Id we’d use and next to it is the ClientSecret.

wp-content/uploads/2022/05/get-app-id-secret.png

Click on Show and copy the AppSecret. Also don’t forget to add your domains in the AppDomains section, including localhost.

With this, we complete configuring the facebook app and have the clientId and clientSecret in place for the next step.

Install Authentication.Facebook package in .NET Project

Once we’re done with obtaining clientId and clientSecret, integrating the provider onto our login module is simple. We’d need to install the Authentication module for AspNetCore which provides facebook authentication middleware.

dotnet add package Microsoft.AspNetCore.Authentication.Facebook

Once this is installed, we can next add an authentication middleware to our application pipeline which does the needful.

Add Authentication middleware to ASP.NET Core Pipeline

In the ConfigureServices() method, we’d add an authentication service to our service pipeline and then hookup the Facebook middleware to be called whenever requested for authentication.

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        /* Startup.ConfigureServices() method */


        var oidcProviders = new OidcProviders();
        Configuration.Bind("Oidc", oidcProviders);


        // we'll use the oidcProviders later
        services.AddSingleton(oidcProviders);


        var provider = oidcProviders.Where(x => x.ProviderName == "facebook");
        var builder = services.AddAuthentication(options =>
        {
            options.DefaultScheme = SocialAuthenticationDefaults.AuthenticationScheme;
            options.DefaultSignInScheme = SocialAuthenticationDefaults.AuthenticationScheme;
        })
        .AddCookie(SocialAuthenticationDefaults.AuthenticationScheme);


        builder.AddFacebook(options =>
        {
            options.SaveTokens = true;
            options.ClientId = provider.ClientId;
            options.ClientSecret = provider.ClientSecret;
            options.Events.OnTicketReceived = (context) =>
            {
                Console.WriteLine(context.HttpContext.User);
                return Task.CompletedTask;
            };
            options.Events.OnCreatingTicket = (context) =>
            {
                Console.WriteLine(context.Identity);
                return Task.CompletedTask;
            };
        });


    }
}

Modifying Login action and Handling Callback for Facebook Login

Back in our login action where we’re creating a ChallengeResult() for an input provider, we’d modify the code a bit to use the Facebook scheme for invoking the middleware we configured in the step before.

public class UserController : Controller
{
    /* UserController.ExternalLogin() which handles the redirect to provider */


    [HttpGet, Route("[controller]/ExternalLogin")]
    public IActionResult ExternalLogin(string returnUrl, string provider = "google")
    {
        string authenticationScheme = string.Empty;


        // Logic to select the authenticationScheme
        // which specifies which LoginProvider to use
        // comes in here
        authenticationScheme = FacebookDefaults.AuthenticationScheme;


        var auth = new AuthenticationProperties
        {
            RedirectUri = Url.Action(nameof(LoginCallback), new { provider, returnUrl })
        };


        return new ChallengeResult(authenticationScheme, auth);
    }


}

Also, in our View for Login, let’s add one button to invoke this endpoint.

<div class="col-lg-12 p-2">
    <a target="_self" href="~/user/ExternalLogin?provider=facebook" class="btn btn-block btn-primary">
        <span class="icon-facebook2"></span> Facebook
    </a>
</div>

Testing Pieces together for Functionality

Now we’ve joined all the dots together and have the necessary logic in place for authentication, let’s run this build and see for ourselves how this works.

When we click on the Facebook button above, the /user/externallogin action will be called, which returns a ChallengeResult() onto the Facebook middleware.

This results in a redirection to facebook login page where the user enters login credentials.

How it works in Action

The validation happens at the facebook end itself, and once the login is successful Facebook returns back an authorization code which is captured and processed within the middleware itself and the redirection happens to the Callback endpoint we also passed with the ChallengeResult().

In the LoginCallback endpoint, we Authenticate against the AuthenticationScheme we defined for social login, and set up the auth cookie.

We read the necessary claims from the Identity setup by the middleware and use it to create a user profile in the database for later use.

Within the UserRepository where the domain logic happens, we can optionally call userManager.SignIn() with additional parameters (in our case we pass the created db primary key for later use) which will be set to create a new identity profile.

Finally, this identity setup within the application can be used to provide users with application related functionalities without having for the application to worry about user authentication and validation since it’s now delegated to the identity provider.

When a user would want to sign out, we’d call SignOut endpoint on the UserController which internally removes the auth cookie from the browser thereby removing user login session.

wp-content/uploads/2022/05/app-login.png
wp-content/uploads/2022/05/fb-redirect.png
wp-content/uploads/2022/05/profile-capture.png

I have also explained how to add Google Login as a part of the Social Logins with .NET series. You can check out the article here – https://referbruv.com/blog/posts/social-authentication-in-aspnet-core-adding-google-login


Buy Me A Coffee

Found this article helpful? Please consider supporting!

Ram
Ram

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity. You can connect with me on Medium, Twitter or LinkedIn.

Leave a Reply

Your email address will not be published. Required fields are marked *