Asp .net core 3 and Google login 5


.net core
Accessing the Google apis with asp .net core can be a little tricky to set up. I have seen a lot of questions about it on Stack overflow the last few years. Today I thought we would have a look at setting up the Google Apis .net client library to an Asp .net core 3 application and display the currently authenticated users name.

Configuration

The first thing we will need is to create a new project of Asp .Net Core Web application, I will be using the MVC template. In order to use the Google api .net client library with ASP. net core we will need to add two NuGet Packages to our project. The first is Google.Apis.Auth.AspNetCore3
which adds all the authorization and authentication communication. Then we will need to add the Google.apis.peopleservice, which will give us access to all the methods we need in order to access the Google People api.

  • Install-Package Google.Apis.Auth.AspNetCore3 -Version 1.51.0
  • Install-Package Google.Apis.PeopleService.v1 -Version 1.51.0.2273

The Google people API is a free api that returns profile information about the currently authenticated use.

Configuration Authorization

Now we will configure the authorization inside the startup.cs file. We will need to add a client id and client secret. You will need to create web application credentials on Google Developer Console. If you haven’t done this already go do so now, if you have any issues I have a video you can go watch to see how to do that. Make sure to configure the redirect uri properly for your application or you will get redirect_uri_missmatch error.

How to create Google Oauth2 web application credentials.json.

Add Constants

In Startup.cs we will need to configure the authorization, this is where we will pass our client id and client secret. I have just added them as a constant here, you may want to consider adding them to the app settings. You can get these values from the Credeintals.json you downloaded from Google Developer console or from the console itself.

 private const string ClientId = "[YOUR CLIENT ID]";
 private const string ClientSecret = "[YOUR SECRET]";

Configure Service

Now we need to configure the service. In the configuration method of our startup.cs file we will configure AspNetCore3 for use in our app. Notice how
the client id and client secret are passed to the AddGoogleOpenIdConnect extension method. This will allow our application to use OpenIdConnect to Authenticate a user and authorize our application to access their private profile data.

 // This configures Google.Apis.Auth.AspNetCore3 for use in this app.
 services
     .AddAuthentication(o =>
     {
         // This forces challenge results to be handled by Google OpenID Handler, so there's no
         // need to add an AccountController that emits challenges for Login.
         o.DefaultChallengeScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme;
         // This forces forbid results to be handled by Google OpenID Handler, which checks if
         // extra scopes are required and does automatic incremental auth.
         o.DefaultForbidScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme;
         // Default scheme that will handle everything else.
         // Once a user is authenticated, the OAuth2 token info is stored in cookies.
         o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
       })
       .AddCookie()
       .AddGoogleOpenIdConnect(options =>
       {
          options.ClientId = ClientId;
          options.ClientSecret = ClientSecret;
           });

Configure

The last thing we need to do in startup is to ensure that both UseAuthencation And UseAuthorization are added in the Configure method.

app.UseAuthentication();
app.UseAuthorization();

Controller

Now we can move on to the controller. In the main controller I have added a method called UserProfile.

The method contains a GoogleScopedAuthorize attribute, this is where we define that our method needs authorization in order to run and which scope we need.

Then we can create a PeopleServiceService passing it the authorization that we created in our startup.cs file.

Finally we call the Google People api requesting the names information for the currently authenticated user.

 [GoogleScopedAuthorize(PeopleServiceService.ScopeConstants.UserinfoProfile)]
 public async Task UserProfile([FromServices] IGoogleAuthProvider auth)
        {
            var cred = await auth.GetCredentialAsync();
            var service = new PeopleServiceService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = cred
                });
            

            var request = service.People.Get("people/me");
            request.PersonFields = "names";
            var person = await request.ExecuteAsync();

            return View(person);
        }

Create view

Then I will add a very simple view, which will display the data returned by the api. In this case my display name.

@model Google.Apis.PeopleService.v1.Data.Person

@{
    ViewData["Title"] = "Hello";
}
<p>Use this page contains information about the authenticated user</p>

@if (Model != null)
{
    <p>
        <strong>UserName:</strong> <code>@Model.Names.FirstOrDefault()?.DisplayName</code>
        <strong>UserName:</strong> <code>@Model.EmailAddresses.FirstOrDefault()?.Value</code>
    </p>
}

Add link

As the default project contains a menu at the top of the page i have simply added a new menu item which i can use to access my new method.

<li class="nav-item">
     <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="UserProfile">UserProfile</a>
</li>

Run app

Ok lets run it.

redirect_uri_missmatch Error

Remember if you get the redirect_uri_missmatch error, this is a configuration issue over on google developer console, I have a video which I created for just
this cause you can go check that out now and it will show you in two minutes how to fix it.

Google OAuth2: How the fix redirect_uri_mismatch error. Part 2 server sided web applications.

Conclusion

The same approach can be used for most of the Google APIs you just need to create a different service for each of the apis and make sure that you are requesting the correct scope for the method it is you are trying to access.

If you would like to see another article on how to do this with say Google drive, google calendar or even the YouTube api please let me know in the comment section below and I would be happy to create a new tutorial dedicated to each of the apis.

I have a companion Video up on my YouTube channel to go along with this video if you would like to see how I did this.


About Linda Lawton

My name is Linda Lawton I have more than 20 years experience working as an application developer and a database expert. I have also been working with Google APIs since 2012 and I have been contributing to the Google .Net client library since 2013. In 2013 I became a a Google Developer Experts for Google Analytics.

Leave a comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

5 thoughts on “Asp .net core 3 and Google login

  • Mike Joy

    Thank you for this useful posting.
    A couple of questions/notes:
    – the videos about how to fix the uri rediect error (via the google developer console) are not working for me, I get a message “qhz1rs6lzhq’s server IP address could not be found.”
    – I would welcome a posting on how the middleware and GoogleScopedAuthorize and IGoogleAuthProvider play together. I find that some scopes work fine, and some scopes give me a “ISecurityTokenValidator” error which I have no idea how to debug because I don’t understand how these things all fit together.

    Thanks again.

    • Linda Lawton Post author

      Sounds like you are mixing authorization and authentication. Oauth2 does not have an id token and should not be validated. Open id connect, signin, authorization has an id token that can be validated.

  • Umar Shareef

    Hi Linda,
    I watched your video and code. I am able to login with Google and get claims. But on trying to get People data I am getting an error.

    InvalidOperationException: The AuthorizationPolicy named: ‘GoogleScoped: https://www.googleapis.com/auth/userinfo.profile‘ was not found.

    I am writing code in .NET 6. I have also enabled People API from the Google console. Can you please suggest if I am missing something?