How to Implement Google Login in ASP.NET Core

In this section, we shall see how we can integrate the created login module with Google login, so that we can have users redirected to Google Signin when they click on login and be redirected back to the application to create a profile and store the created profile in the database

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. Next, we saw how we can integrate the login module with Facebook for providing user login.

In this section, we shall see how we can integrate the created login module with Google login, so that we can have users redirected to Google Signin 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 console.developers.google.com and then create an application for us to get started.

Log into https://console.developers.google.com and click on Create Project. A New Project window opens up, enter the App name and other details and click on create.

wp-content/uploads/2022/05/create-google-project.png

Once created, select the Configure Consent Screen option in the left panel, this is where we configure what information will be shown to the user when login using their Google credentials.

wp-content/uploads/2022/05/oauth-consent.png

Once this is completed, click on Credentials and then Create Credentials. Since we’re doing an OAuth login, click on OAuth Client ID. In the screen, fill the details such as AppName and others.

wp-content/uploads/2022/05/create-credentials.png

Under the Redirect Urls, enter https://localhost:5001/signin-google, which is where the redirection happens. Once done, click on Save and you have a popup showing up the ClientId and ClientSecret.

wp-content/uploads/2022/05/credentials-created.png

Copy these values and we’re good to go to the next step.

Installing Authentication.Google 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 google authentication middleware.


> dotnet add package Microsoft.AspNetCore.Authentication.Google

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 Google 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 == "google");
var builder = services.AddAuthentication(options =>
{
    options.DefaultScheme = SocialAuthenticationDefaults.AuthenticationScheme;
    options.DefaultSignInScheme = SocialAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(SocialAuthenticationDefaults.AuthenticationScheme);

builder.AddGoogle(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 = GoogleDefaults.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=google" 
        class="btn btn-block btn-primary">
            <span class="icon-google"></span> Google
    </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 Google Signin button above, the /user/externallogin action will be called, which returns a ChallengeResult() onto the Google middleware. This results in a redirection to Google login page where the user enters login credentails. The validation happens at the Google end itself, and once the login is successful Google 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 Flow:

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

Next, we shall look at how we can combine these two auth flows into single component so as to provide a multi-login experience to the user.

Sriram Mannava
Sriram Mannava

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity.

One comment

Leave a Reply

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