Tag - Authentication

Facebook Authentication Setup in ASP.NET
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. 

ASP .NET Core Two-Factor Authentication
Feb 21, 2024

What is Authentication?  Authentication is the process of validating the identity of a user or system attempting to access a protected resource. In C# programming, authentication is commonly implemented in various scenarios, including web applications, desktop applications, and services.  Types of Authentications  Basic Authentication  Password-based Authentication  Multi-Factor Authentication  Token-based Authentication  Let’s understand authentication with example. Here I am taking one example of MFA (Two-factor authentication).  Step 1: Create the MVC Web Application  Open Visual Studio and select File >> New >> Project. After selecting the project, a “New Project” dialog will open. Select ASP.NET Core web app (Model-View-Controller) and press Next and enter project name and click Next.      Choose 'Individual Account' as the authentication type and click 'Create' to generate the project.      Step 2: Adding QR Codes to configure two-factor authentication  We will be using a QR code to configure and sync the Google authenticator app with our web app. Download the qrcode.js JavaScript library from https://davidshimjs.github.io/qrcodejs/ and put it into the “wwwroot\lib” folder in your application. Now, your “wwwroot” folder will have the following structure.      Now, Add new scaffolded item in your project by right click on Area folder and select New scaffolded Item under Add section.  Select Identity section on left sidebar and click on Add.      Now, Select the identity files that you have to add to your project but select file “Account/Manage/EnableAuthenticator” is compulsory for 2FA.  Select the DbContext Class of your project and click on add.   Open the “Views\Manage\EnableAuthenticator.cshtml” file. You will find @section Scripts at the end of the file. Put the following code in it.  @section Scripts { @await Html.PartialAsync("_ValidationScriptsPartial") <script src="~/lib/qrcode/qrcode.js"></script> <script type="text/javascript"> new QRCode(document.getElementById("qrCode"), { text: "@Html.Raw(Model.AuthenticatorUri)", width: 200, height: 200 }); </script> }   Note: Change your script path as per your folder structure.  This “EnableAuthenticator.cshtml” file already has a div with the id “qrCode” (see the code snippet below). We are generating a QR code inside that div using the qrcode.js library. We are also defining the dimensions of the QR code in terms of width and height.  So finally, your “EnableAuthenticator.cshtml” file will look like this. @page @model EnableAuthenticatorModel @{ ViewData["Title"] = "Configure authenticator app"; ViewData["ActivePage"] = ManageNavPages.TwoFactorAuthentication; } <partial name="_StatusMessage" for="StatusMessage" /> <h3>@ViewData["Title"]</h3> <div> <p>To use an authenticator app go through the following steps:</p> <ol class="list"> <li> <p> Download a two-factor authenticator app like Microsoft Authenticator for <a href="https://go.microsoft.com/fwlink/?Linkid=825072">Android</a> and <a href="https://go.microsoft.com/fwlink/?Linkid=825073">iOS</a> or Google Authenticator for <a href="https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2&amp;hl=en">Android</a> and <a href="https://itunes.apple.com/us/app/google-authenticator/id388497605?mt=8">iOS</a>. </p> </li> <li> <p>Scan the QR Code or enter this key <kbd>@Model.SharedKey</kbd> into your two factor authenticator app. Spaces and casing do not matter.</p> <div class="alert alert-info">Learn how to <a href="https://go.microsoft.com/fwlink/?Linkid=852423">enable QR code generation</a>.</div> <div id="qrCode"></div> <div id="qrCodeData" data-url="@Model.AuthenticatorUri"></div> </li> <li> <p> Once you have scanned the QR code or input the key above, your two factor authentication app will provide you with a unique code. Enter the code in the confirmation box below. </p> <div class="row"> <div class="col-md-6"> <form id="send-code" method="post"> <div class="form-floating mb-3"> <input asp-for="Input.Code" class="form-control" autocomplete="off" placeholder="Please enter the code."/> <label asp-for="Input.Code" class="control-label form-label">Verification Code</label> <span asp-validation-for="Input.Code" class="text-danger"></span> </div> <button type="submit" class="w-100 btn btn-lg btn-primary">Verify</button> <div asp-validation-summary="ModelOnly" class="text-danger" role="alert"></div> </form> </div> </div> </li> </ol> </div> @section Scripts { @await Html.PartialAsync("_ValidationScriptsPartial") <script src="~/lib/qrcode/qrcode.js"></script> <script type="text/javascript"> new QRCode(document.getElementById("qrCode"), { text: "@Html.Raw(Model.AuthenticatorUri)", width: 200, height: 200 }); </script> } When we execute the program, a QR code will be generated in this View. Then you can set up two factor authentication using the Google authenticator with the help of this QR code.  Step 3: Configure two-factor authentication  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 the “Update-Database” command and hit Enter. This will update the database using Entity Framework Code First Migrations. Run the application and click on “Register” in the top right corner of the homepage. You can see a user registration page. Fill in the details and click on the “Register” button as shown in the image below.  Upon successful registration, you will be logged into the application and navigated to the home page. Here, you can see your registered Email id at the top right corner of the page. Click on it to navigate to the “Manage your account” page. Select “TwoFactorAuthentication” from the left menu. You will see a page similar to that shown below.       Click on the “Set up authenticator app” button. You can see a QR code generated on your screen — it is asking for a “Verification Code”, also as shown in the image below.    You need to install the Google Authenticator/Microsoft Authenticator app on your smartphone. It will allow you to scan this QR code in order to generate a Verification Code and complete a two-factor authentication setup.  Open Microsoft Authenticator and click on verified IDs at the bottom. Click on “Scan a barcode” and scan the QR code generated by the web app. This will add a new account to Microsoft authenticator and generate a six-digit pin on your mobile screen. This is our two-factor authentication code. This is a TOTP ( time-based one-time password). You can observe that it keeps on changing frequently (life span of 30 seconds).  Put this pin in the Verification Code textbox and click on verify. Upon successful verification, you will see a screen similar to the one shown below. This will give you the recovery codes for your account that will help to recover your account in case you are locked out. Take a note of these codes and keep them somewhere safe.    Logout of the application and click on login again. Enter your registered email id and password and click on login.    Now you can see a the two-factor authentication screen asking for the Authenticator code. Put in the code that is generated in your Google Authenticator app and click on Login. You will be successfully logged into the application and navigated to the home page. 

magnusminds website loader