Implementing Facebook Authentication in ASP.NET: A Step-by-Step Guide

Mar 18, 2024

Introduction:

Integrating Facebook authentication into your .NET project offers a user-friendly login option, allowing users to sign in with their Facebook credentials. This guide will walk you through the steps to implement Facebook login, enhancing user convenience, trust, and providing access to user data.

Creating a Demo for Facebook Authentication in .NET

Step 1: Set Up .NET Project 

1. Create a new ASP.NET MVC project using Visual Studio or your preferred IDE. 

Step 2: Create Facebook Developer App 

2. Go to the [Facebook Developer Portal] : https://developers.facebook.com/

3. Create a new app. 

4. Configure the app details and obtain the App ID and App Secret. 

  

Step 3: Configure Facebook Authentication in .NET Project 

5. In your .NET project, open `Startup.cs`. 

6. Configure Facebook authentication: 

 services.AddAuthentication(options => 
   { 
       options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; 
       options.DefaultChallengeScheme = FacebookDefaults.AuthenticationScheme; 
   })
   .AddCookie() 
   .AddFacebook(options => 
   { 
       options.AppId = "Your-Facebook-App-ID"; 

       options.AppSecret = "Your-Facebook-App-Secret"; 

       options.CallbackPath = new PathString("/Auth/FacebookCallback");
   }); 

Step 4: Create AuthController 

7. Create an `AuthController` with actions for Facebook login and callback: 

 public class AuthController : Controller 
   { 
       public IActionResult Index() 
       { 
           return View(); 
       } 
       [HttpGet] 
       [Route("signin-facebook")] 
       public async Task<IActionResult> FacebookCallback() 
       { 
           var result = await HttpContext.AuthenticateAsync("Facebook"); 
           if (result.Succeeded) 
           { 
               // Authentication succeeded. Add your logic here. 
               return RedirectToAction("Index", "Home"); 
           } 
           // Authentication failed. Handle the error. 
           return RedirectToAction("Login", "Account"); 
       } 
       public IActionResult FacebookLogin() 
       { 
           var properties = new AuthenticationProperties 
           { 
               RedirectUri = Url.Action("https://localhost:7135/Auth/FacebookCallback"), 
           };  
           return Challenge(properties, FacebookDefaults.AuthenticationScheme); 
       } 
   } 

Step 5: Implement Facebook Login Button 

8. In your `Index.cshtml` or another appropriate view, add a button for Facebook login:

 <h1>Facebook Authentication</h1> 
<button class="btn btn-primary"><a style="color:white" asp-controller="Auth" asp-action="FacebookLogin">Login with Facebook</a></button> 

Step 6: Update App Settings 

9. In the Facebook Developer Portal, update the "Valid OAuth Redirect URIs" with `https://localhost:7135/Auth/FacebookCallback`. 

  •   Login Facebook > Settings.

Step 7: Run and Test 

10. Run your .NET project and test the Facebook authentication by clicking the "Login with Facebook" button. 

  

  •  Click on Login with Facebook > Continue.
  • You can create Successful login in redirect logic.

You Can also use JavaScript SDK to use authenticate in Your project I n our case will use MVC 

  •   Here will use the same app we already create just we will Update the controller action to JS function provided by "Meta Developer" Quick Start

  • Add this JavaScript code in your view where your login button is available 
<button class="btn btn-primary"><a style="color:white" onclick="loginWithFacebook()">Login with Facebook</button>

<script>
    window.fbAsyncInit = function () {
        FB.init({
            appId: '1438230313570431',
            xfbml: true,
            version: 'v19.0'
        });
        FB.AppEvents.logPageView();
    };
    (function (d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) { return; }
        js = d.createElement(s); js.id = id;
        js.src = "https://connect.facebook.net/en_US/sdk.js";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
    function loginWithFacebook() {
        FB.login(function (response) {
            if (response.authResponse) {
                // User is logged in and authorized your app
                console.log('Successful login for: ' + response.authResponse.userID);
                console.log(response);
                debugger;
                window.location = "https://localhost:44304/Auth/SuccesfullLogin";
            } else {
                // User cancelled login or did not authorize your app
                console.log('Login cancelled');
            }
        }, { scope: 'public_profile,email' }); // Specify the required permissions
    }
</script>
  • Now we Have to add js.src link in your JS functions is need to be Added in Meta developer App

In our case it is : 

 https://connect.facebook.net/en_US/sdk.js
  • will go to again Use cases > customize > settings.
  •  Will add our link in "Allowed Domains for the JavaScript SDK" section

Make sure "Login with the JavaScript SDK" toggle is "Yes".

Now, you have a comprehensive guide for creating a demo on Facebook authentication in a .NET project. Share this guide, and users can follow each step to implement Facebook login functionality in their ASP.NET applications. 

Hrutvik Barot

About the Author

Hrutvik Barot

Experienced Dotnet developer with nearly 2 years of expertise, adept at crafting robust software solutions. A dedicated and fast learner committed to continuous exploration of cutting-edge technologies for professional and personal growth.