We use cookies to provide you with a great user experience, analyze traffic and serve targeted promotions.   Learn More   Accept
Card image cap

Social Authentication in ASP.NET Core - Adding Facebook Login

ASP.NET Core  • Posted 2 months ago

In the previous sections, 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 for 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, so that we can have users redirected to Facebook when they click on login and be 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:

Generating ClientId and Client Secret

Like we discussed before, 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 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 which 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.

To create an application, we'd go to developers.facebook.com and then create an application for us to get started.

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.

data/Admin/2020/4/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.

data/Admin/2020/4/configure-fb-login.PNG

Now that we have setup the Facebook Login, we would need to pick up the ClientId and ClientSecret of this created application. On the left panel, click on Settings below Dashboard, which will openup 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.

data/Admin/2020/4/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.

Installing Authentication.Facebook package

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.

Adding Authentication middleware

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


/* 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

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


/* 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>

End-to-End Testing

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 credentails. 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 defineed for social login, and sets up the auth cookie. Next, we read the necessary claims from the Identity setup by the middleware and use it to create 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 user 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 user would want to signout, we'd call SignOut endpoint on the UserController which internally removes the auth cookie from the browser thereby removing user login session.

End Result Flow:

data/Admin/2020/4/app-login.PNG data/Admin/2020/4/fb-redirect.PNG data/Admin/2020/4/profile-capture.PNG

Next, we'd continue with adding Google Login to our Login Module.

asp net core facebook login .net core facebook login facebook social login asp.net core 3.1 social login asp.net core