ASP.NET Core Google Authentication

Process of Sign In With Google In The ASP.NET Core Application.

Pritomsarkar
.Net Programming
9 min readMay 11, 2021

--

Overview

You see, nowadays many people have accounts already created with third-party applications like Microsoft, Google, Facebook, Twitter, etc. We actually trust these third-party applications and use them to authenticate and identify who the user is. So for that, these third-party applications are called trusted identity providers.

If a user wants to signin to our application to use his Google account, they will click the created Google button.

Prerequisites

I expect you to have knowledge of object-oriented programming concepts in C#. I assume you know .NET Core concepts especially the MVC pattern also.

To code along with me, you will have to install the .NET Core 2.2, as well as Visual Studio. You can also use another IDE instead of a visual studio. You can find a link to the Github repository end of this article. Also, I will highly encourage you to read this article for a better understanding.

Environment Setup

Open Visual Studio 2017. Create a project “Asp.Net Core Web Application(.Ne Core)” with an MVC pattern Template. You Can name this project whatever you want.to code along with me, you have to download this source code.

Create google OAuth credentials

we need to ClientId and Client Secret in your application for Google authentication. Navigate to the following website and login with your Google credentials https://console.developers.google.com and then log in here with your G-Mail.

Once you log in, the first step creates a new project if you don’t have one already. at this moment, I don’t have any projects.so let's create a new project by clicking on Select a project.

And then select the NEW PROJECT.

now give you a meaningful name for your project. I give my project name is Google auth STS. STS stands for Security Token Service. because we are using this project here, to provide Identity service for our .NET Core application.

Let's click CREATE to create this new project.

Once our new project is created, our next step is to enable Google class API.

for that, click on this library navigation menu on the left. but some reason if you don’t see this navigation menu then click the Google APIs logo and then you will find this menu bar. Once you click on this library menu then

You get a search page and search here Google+ API and click on that.

and then click the ENABLE button to enable this service.

Next, you need to configure the OAuth consent screen. If you do not see the OAuth consent screen tab, click on the Google APIs banner image on the top left-hand corner. now click on this OAuth consent screen.

so now on this screen, the only required field is the Application name. this is the name shown to the user on the consent screen. at the moment we are creating these OAuth credentials for our .NET Core application.

The user type is External.

I have given above the app name, user support mail, and Developer contact information email address. Now scroll down and then you have to click Save & Continue.

and after that, you have to click the credentials navigation bar. and then CREATE CREDENTIALS=>OAuth client ID.

so now on this screen select Web Application. because that is the type of our client application. next, provide a name for the client. I gave this name Identity client. next Authorised JavaScript origins, which is the URI at which the client application is hosted.

at the moment our project still running on our local machine. so to get the URI at which our project hosted in the local machine, right-click in project name in the solution explorer and go to the properties window.https is more secure than http.at first, enable SSL.then copy this URL and paste it in the App URL text box. so that is the URL, at which our application is hosted.

so let’s copy this URL and paste it Authorised JavaScript origins’ text box.

finally, you have to configure Authorised redirect URIs.this is the URI to which user is redirected to after they are authenticated by Google. and the default is the URI at which our application is hosted and this path signin-google and finally click the CREATE button.

So now you get the Client_Id and Client_Secret.

I have hidden my Client_Id and Secret_Id for my security purposes.

we need both of these IDs to integrate google authentication in our .NET Core project.

Setting up the UI for Google authentication.

so now you have to configure Google authentication for your .NET Core application. we do that in our startup class.

The code required for Google authentication including this AddGoogle() method is present in Microsoft.AspNetCore.Authentication.Google NuGet package. Since I am using ASP.NET Core 2.2, this package is automatically included in the project as part of the meta-package. If you are using older versions of ASP.NET Core you have to manually install this NuGet package.

The model for login view we have LoginViewModel class. Include ReturnUrl and ExternalLogins properties.ReturnUrl is the URL the user was trying to access before authentication. We preserve and pass it between requests using the ReturnUrl property, so the user can be redirected to that URL upon successful authentication.

ExternalLogins property stores the list of external logins like(Facebook, Google, etc) that are store in our application.

I have to show all external login(Facebook, Google, etc) on the login page. for that, I have to add some code to show these. create ReturnUrl and ExternalLogins properties of LoginViewModel and then pass the view.

GetExternalAuthenticationSchemesAsync() method of SignInManager service, returns the list of all configured external identity providers like (Google, Facebook, etc) and At the moment we only have one external identity provider configured and that is Google.

now I have to add some code in the login view to show a list of an external provider. We are looping through each external login provider we have in Model.ExternalLogins.

Since the button name is set to provider, asp.net core model binding maps the provider name(@provider.name) which is Google to provider parameter on the ExternalLogin action.

If you run your application then you will find:-

if you click the Google button, by the way, that button is a submit type of button in your view code. then you find an error and that is page not found. because you are not created ExternalLogin action yet in your AccountController.Now you have to create an ExternalLogin action.

ChallengeResult also implements IActionResult and ChallengeResult Redirect to the user to the external login provider Sign In page. so our case it’s Google Sign In page.

If you run your application and click the Google button then,

Then you will see your project name. now click your mail. give password and log in. but at this time, you will find an error. because you are not created ExternalLoginCallback in your Accountcontroller.

let’s include the ExternalLoginCallback method in our Accountcontroller. so this method has two input parameters,returnUrl, and remoteError.first we check if the first parameter value is null, if it is then we initialize it to the application root URL.otherwise it will have the value of returnUrl.next, we will check the second parameter remoteError.if it is not null, that means we have received some error information from the external LogIn provider Google for example.

next, we want to get the external login information. so for that, we used this method GetExternalLoginInfoAsync() of the signInManger service. if the info object is null, that means we have not received any external login information. so here we add an error message in ModelState and redisplayed the login view.

if the external login info object is not null,that means we have received login information from the external login provider,in our case Google.and then we want to sign the user in using the external login provider.so for that we use ExternalLoginSignInAsync method of the signInManager service.into this method we pass the LogInProvider,ProviderKey,a persistent cookie and two factor authentication.signInResult.when you first try to external login,ExternalLoginSiginAsync is failed.that’s because the parameter of LoginProvider Google with this provider key,actually when you try to first external login ,this time will not have a corresponding login row in our AspNetUserLogin table.so genarally signInResult is not succeeded at this time.so now will work code under the else.

so at first, you will found your email address from google. because you used google as an external logIn provider that means email is not null.next, code search your external email address to your AspNetUser table.if you will found your external email address in your AspNetUser table, that means the external user has a local account.this time will add a row in the AspNetUserLogin table and this is done by AddLoginAsync() of the userManager service.after a row is added in AspNetUserLogin, this code sign the user and redirect him to the returnUrl.

But what if you don’t find a local user account with the provided email claim value?if you can’t find the user, that means the user is null,for that you have to create a local user account for external user.so we create a new instance of the Identity user class populate the username and email properties and pass the user object to the CreateAsync() method of the userManager service.that creates a new record in the AspNetUser table.and then we add a login for that new user and sign him in.

Without an email claim, we can not continue any further.so we set ErrorTitle and ErrorMessage on the Viewbag object.

If you run your application and click the Google button then select your Gmail account, then give your id and password to log in to your Gmail.then you will see an output as expected.

Congratulations!You successfully log in to your account using your external login provider.

If you will see your AspNetUser and AspNetLogins tables then you will found an interesting thing.in AspNetUser table we have new row,look at the passwordhash column,it’s null! actually we have don’t need password for this user.actually,we don’t have to maintain that anymore.because this user is going to an external login provider Google account.

If you now look at the AspNetLogins table, then you will see you have a new row for external login.now look at the userId column.this is an foreignkey refferencing that is the id, which was created a local account for external login.

AspNetUsers table

AspNetUsers table

AspNetUserLogins table

AspNetUserLogins table

Conclusion

You have successfully logged in to your application using Google.

Hope you guys enjoy this article. You can download the source code to my Github Repository.

Happy Coding :)

--

--