(WebApi C# ASP.NET Core) Social Media Authentication in WebApi

WebApi can be protected through social media authentication also. The first step is to obtain a client id and a client secret by creating an app on a social media platform. Then these values are used to configure authentication services for that platform. In this tutorial we present the sequence of steps required to gain authorization to a web api protected by google authentication.
(Rev. 31-Oct-2024)

Categories | About |     |  

Parveen,

Getting Started with Pre-Requisites

First of all create an OAuth App by following the steps explained in this video - https://youtu.be/55z-SOpiBTE.

Secondly, take note of the nuget package that you will have to add to your ASPNET Core project - Microsoft.AspNetCore.Authentication.Google.


Install-Package Microsoft.AspNetCore.Authentication.Google

This package contains most of the boilerplate code for completing the login process.

Video Explanation (see it happen!)

Please watch the following youtube video:

Program.cs file

I have already created an ASPNET Core project that you can obtain from the downloads attached to this video.

Open the solution explorer and locate the Program.cs file. Double-click to open it!

You will have to install this nuget package for the code to compile. Then we have the namespaces, and the usual calls to CreateBuilder and AddRazorPages


// Install-Package Microsoft.AspNetCore.Authentication.Google 

using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.Google;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;

var builder = WebApplication.CreateBuilder();

builder.Services.AddRazorPages();

builder
    .Services.AddAuthentication(options =>
    {
      options.DefaultScheme = 
        CookieAuthenticationDefaults.AuthenticationScheme;

      options.DefaultChallengeScheme = 
        GoogleDefaults.AuthenticationScheme;
    })
    .AddCookie()
    .AddGoogle(googleOptions =>
    {
      
      // refer: https://youtu.be/55z-SOpiBTE 
      // DON'T HARDCODE - USE Environment or Settings 
      googleOptions.ClientId = "441--your own--";

      googleOptions.ClientSecret = "GO---your-own-i";

      googleOptions.Events.OnTicketReceived += (ticket) =>
      {
        // get the email 
        String email = ticket.Principal.FindFirstValue(ClaimTypes.Email);

        // make a database check if email is registered 
        bool isEmailRegistered = true; 

        if (isEmailRegistered)
        {
          // make a database check of the role 
          // suppose the role is found Admin 
          String? role = "Admin";

          ticket.Principal?.AddIdentity(
            new ClaimsIdentity(new[] { new Claim(ClaimTypes.Role, role) },
            GoogleDefaults.AuthenticationScheme
            ));

        }
        else
        {
          // access denied if email not registered 
          ticket.Response.StatusCode = StatusCodes.Status401Unauthorized;

          // halt further processing 
          ticket.HandleResponse();
        }

        return Task.CompletedTask;

      };

    });

builder.Services.AddAuthorization();

var app = builder.Build();

app.UseAuthentication();

app.UseAuthorization();

app.MapRazorPages();

app.MapGet("/info", 
  [Authorize( 
    AuthenticationSchemes = GoogleDefaults.AuthenticationScheme,
    Roles = "Admin") 
  ] () =>
{
  return Results.Ok("You are in!");
});

app.Run();

Authentication service is configured next, with the DefaultScheme and DefaultChallengeScheme set to "Cookies" and "Google" exactly as shown.

The call to AddCookie configures various cookie defaults.

The most important settings are done through the AddGoogle extension. The values for ClientId and ClientSecret must match the ones shown on your google console page.

Lastly, we have subscribed to the TicketReceived event. This callback executes after a user has successfully authenticated from the login page of google.

We can extract the email at this point. Alternatively we could have obtained NameIdentifier, a unqiue id maintained by social media platforms.

Once you have the email id, then you can process it in whatever manner you like.

For instance, you can determine if the email exists in the project database. Then you can assign a role to the user.

We have assumed that the user is assigned the Admin role. Next, add this role to the ClaimsPrincipal.

If the user fails authentication, send a 401 - unauthorized response.

After that we have the usual lines for configuring the middleware. And towards the end we have a web api that requires authentication with google authentication scheme. The web api also sets the Role property to restrict access to users of an Admin role.

Run the Project

Run the project to open the home page. It ensures that the server is up and running.

Send a GET request to the /info end-point. But since this API requires authorization, we are redirected to the google login website.

See the linked video for a clearer explanation.

Click on the test email and make a login. Allow the process to complete.

We observe that the api executes successfully.

Thus we have a working example of google based authentication and authorization. You can similarly implement Facebook, Twitter, and other authentications. Thanks!


This Blog Post/Article "(WebApi C# ASP.NET Core) Social Media Authentication in WebApi" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.