ASP.NET Core

Authentication Using Google In ASP.NET Core 2.0

Introduction

Sometimes, we want the users to log in using their existing credentials of third-party applications, such as Facebook, Twitter, Google etc. into our application. In this article, we are going to look into authentication of ASP.NET Core app using a Google account.

Prerequisites

  • Install .NET Core 2.0.0 or above SDK from here.
  • Install the latest version of Visual Studio 2017 Community Edition from here.

Create MVC Web Application

Open Visual Studio and select File >> New >> Project. After selecting the project, a “New Project” dialog will open. Select .NET Core inside Visual C# menu from the left panel. Then, select “ASP.NET Core Web Application” from available project types. Put the name of the project as GoogleAuth and press OK. Refer to this image.

After clicking OK, a new dialog will open asking you to select the project template. You can observe two drop-down menus at the top left of the template window. Select “.NET Core” and “ASP.NET Core 2.0” from these dropdowns. Then, select “Web application(Model-View-Controller)” template. Click on Change Authentication button, a “Change Authentication” dialog box will open. Select “Individual User Account” and click OK. Now, click OK again to create our web app.

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 Update-Database command and hit enter. This will update the database using Entity Framework Code First Migrations.

Press F5 to run the application. You can see a homepage, as shown below.

Note the URL from the browser address bar. In this case, the URL is http://localhost:51792/. We need this URL to configure our Google app which we will be doing in our next section.

Create Google app

We need to create a new Google app on Google API console. Navigate to https://console.developers.google.com/projectselector/apis/library and log in using your Google account. If you do not have a Google account, you need to create one. You cannot proceed without a Google account. Once you have logged in, you will be redirected to API Manager Library page, similar to the one shown below.

Click on Create button to move to “New Project” page where you need to create a new project. The “Project name” field will be populated automatically with a default name provided by Google. If you want then you can override that with your own custom name. For this tutorial we will be using the default name. Accept the terms of service and then click on Create button.

Your project will be created successfully and you will be redirected to API Library page similar to one shown below.

Search for Google+ API in the search bar and select Google+ API from the search results. Refer to the below image.

After selecting the Google+ API option, you will be redirected to a page as shown below, where you need to click on the Enable button.

After this the Google+ API will be enabled and you will be redirected to API home page. Click on Create credentials button on the right side of page to configure the secrets for your API.

You will see an “Add credentials to your project” form.

This form has three sections.

Fill in the details of the sections as mentioned below

Section 1 – Find out what kind of credentials you need

  • Which API are you using? – Google+ API
  • Where will you be calling the API from? – Web server (e.g. node.js, Tomcat)
  • What data will you be accessing? – User data

And click on What credentials do I need button. You will be redirected to section 2

Section 2 – Create an OAuth 2.0 client ID

  • Name – The default value provided by Google.
  • Authorized JavaScript origins- Leave it blank.
  • Authorized redirect URIs – Give the base URL of your application with /signin-google appended to it. For this tutorial the URL will be http://localhost:51792/signin-google. After entering the URL Press TAB to add the value.
After this click on Create client ID button. You will be redirected to section 3

Section 3 – Set up the OAuth 2.0 consent screen

  • Email address– Select your email address from the dropdown. This value is masked in the above image for privacy.
  • Product name shown to users – Enter any product name. Here we are using “AuthDemo” as the Product name.
Important Note
Do not use the word “Google” in your product name. You will be prompted with an error and you won’t be allowed to create the app. This means “GoogleAuthDemo” is an invalid name.

Click on continue.

Your credentials have been created successfully. Click Download to download a JSON file to your local machine with all your application secrets, and then click Done to complete the process.

Open the just downloaded client_id.json file and make a note of ClientId and ClientSecret field. We will need these values to configure Google authentication in our web app.

Configure Web App to use Google authentication

We need to store ClientId and ClientSecret field values in our application. We will use Secret Manager tool for this purpose. The Secret Manager tool is a project tool that can be used to store secrets such as password, API Key etc. for a .NET Core project during development process. With the Secret Manager tool, we can associate app secrets with a specific project and can share them across multiple projects.

Open our web application once again and Right-click the project in Solution Explorer, and select Manage User Secrets from the context menu

A secrets.json file will open. Put the following code in it
{  
  "Authentication:Google:ClientId": "Your Google ClientId here",  
  "Authentication:Google:ClientSecret": "Your Google ClientSecret here"  
}

Now open Startup.cs file and put the following code into ConfigureServices method.

services.AddAuthentication().AddGoogle(googleOptions =>  
{  
    googleOptions.ClientId = Configuration["Authentication:Google:ClientId"];  
    googleOptions.ClientSecret = Configuration["Authentication:Google:ClientSecret"];  
});

In this code section we are reading ClientId and ClientSecret for authentication purposes. So finally, Startup.cs will look like this

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Threading.Tasks;  
using Microsoft.AspNetCore.Builder;  
using Microsoft.AspNetCore.Identity;  
using Microsoft.EntityFrameworkCore;  
using Microsoft.AspNetCore.Hosting;  
using Microsoft.Extensions.Configuration;  
using Microsoft.Extensions.DependencyInjection;  
using GoogleAuth.Data;  
using GoogleAuth.Models;  
using GoogleAuth.Services;  
  
namespace GoogleAuth  
{  
    public class Startup  
    {  
        public Startup(IConfiguration configuration)  
        {  
            Configuration = configuration;  
        }  
  
        public IConfiguration Configuration { get; }  
  
        // This method gets called by the runtime. Use this method to add services to the container.  
        public void ConfigureServices(IServiceCollection services)  
        {  
            services.AddDbContext<ApplicationDbContext>(options =>  
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));  
  
            services.AddIdentity<ApplicationUser, IdentityRole>()  
                .AddEntityFrameworkStores<ApplicationDbContext>()  
                .AddDefaultTokenProviders();  
  
            services.AddAuthentication().AddGoogle(googleOptions =>  
            {  
                googleOptions.ClientId = Configuration["Authentication:Google:ClientId"];  
                googleOptions.ClientSecret = Configuration["Authentication:Google:ClientSecret"];  
            });  
  
            // Add application services.  
            services.AddTransient<IEmailSender, EmailSender>();  
  
            services.AddMvc();  
        }  
  
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
        {  
            if (env.IsDevelopment())  
            {  
                app.UseBrowserLink();  
                app.UseDeveloperExceptionPage();  
                app.UseDatabaseErrorPage();  
            }  
            else  
            {  
                app.UseExceptionHandler("/Home/Error");  
            }  
  
            app.UseStaticFiles();  
  
            app.UseAuthentication();  
  
            app.UseMvc(routes =>  
            {  
                routes.MapRoute(  
                    name: "default",  
                    template: "{controller=Home}/{action=Index}/{id?}");  
            });  
        }  
    }  
}

And with this, our application is ready.

Execution Demo

Launch the application and click Login on the top right corner of the home page

You will be redirected to http://localhost:51792/Account/Login page, where you can see the option to login using Google on the right side of page.

Clicking on Google button will take you to the Google login page where you will be asked to fill in your Google credentials and authorize the Google app to use your Google account. After successful authentication from Google you will be redirected to a registration page inside our application where you need to fill in an email id to tag with your account. The Gmail id that you have used to login will already be populated in the Email id field. If you want to use another mail id you can change it here.

Click register, you will be redirected to home page again but this time you can also see your registered email is on the top right corner.

Conclusion

We have successfully created and configured Google+ app and implemented Google authentication in our ASP.NET Core application.

You can Get the source code from Github

Please note that secrets.json file contains dummy values. Hence replace the values with the keys of your Google app before executing it.

You can also find this article at C# Corner.

You can check my other articles on ASP .NET Core here

See Also

Ankit Sharma

Full Stack Consultant | GDE for Angular | Microsoft MVP | Author | Speaker | Passionate Programmer

View Comments

  • Hi Ankit
    sample code is builded but after scan the generated code from google authenticator or microsoft authenticator , the genereated code returns false always
    "await _userManager.VerifyTwoFactorTokenAsync"

    i've tried your c# corner sample files as well. but not working.
    FYI, i've set my local db and registered data were inserted without any issue.

    Warm regards,
    Saravanan

Recent Posts

Announcing A New Blazor Course

Introduction Blazor is a .NET web framework that allows us to create client-side applications using…

3 years ago

How To Solve Sudoku Using Azure Form Recognizer

Introduction In this article, we are going to create a sudoku solver with the help…

4 years ago

Going Serverless With Blazor

Introduction In this article, we will learn how to implement Azure serverless with Blazor web…

4 years ago

Announcing A Free eBook On Angular and Firebase

Introduction Angular is an open-source framework that allows us to create applications for multiple platforms…

5 years ago

Optical Character Reader Using Angular And Azure Computer Vision

Introduction In this article, we will create an optical character recognition (OCR) application using Angular…

5 years ago

Optical Character Reader Using Blazor And Computer Vision

Introduction In this article, we will create an optical character recognition (OCR) application using Blazor…

5 years ago