How to Sign-In with Google in Angular and use JWT based ASP.NET Core C# API Authentication (RSA)
Tags: angular, dotnet, typescript, webdev
Published: 2021-03-24 20:33:55

This guide shows you all the steps to build an **Angular SPA** with a **focus on authentication**. The single-page web application uses **Sign-In with google** and **angularx-social-login**. The **.NET Core** authentication backend creates **asymmetrically signed tokens** to access another **REST-API**. The sample is **fully working** and can be the basis for a **microservice-like** architecture.

*Authentication workflow and involved components:*

![](https://cdn-images-1.medium.com/max/2000/1*ab78gWYWjmvaG_E-BdFZAA.png)

## Background and Structure of this Guide

When I wanted to create this kind of application I found many descriptions showing some part of it. **This guide brings the parts together.** It is structured so you can optionally test every step before continuing to the next.

**This guide focuses on the key aspects**. I link to other articles for details and download locations of the tools. I use [Visual Studio Community](https://visualstudio.microsoft.com/en/vs/community/) for ASP.NET Core 3.1 development.

### Contents

1. Create the Angular App

2. Add the Login Functionality

3. Authentication API in the .NET Core Backend

4. Use the Authentication API

5. Use the Access Token to Call the Service API

6. Final Thoughts and Outlook

____________________

## 1. Create the Angular App

**Download and install [Node.js/NPM](https://nodejs.org/en/download/).**

Create the folder `C:\dev` and open a command prompt.

**Install Angular** (I used Angular 9 when writing this guide):

    C:\dev>npm install -g @angular/cli

**Create the app:**

    C:\dev>ng new SampleAuthentication

**Install the angularx social login module**

    C:\dev>npm install angularx-social-login

### (Optional) Test the app

Start the app and open it in your browser to see if everything is working:

    C:\dev>ng serve

*Further reading: [Understanding Angular and Creating Your First Application](https://javascript.plainenglish.io/understanding-angular-and-creating-your-first-application-4b81b666f7b4)*

_______________

## 2. Add the Login Functionality

### Get a client ID from google

Create a configuration for your app in the [google developer console](https://console.developers.google.com/). And add the URL of the Angular debug server (http://localhost:4200) as “Authorised JavaScript origin”:

![](https://cdn-images-1.medium.com/max/2000/1*bFGvfQSHNKUuRn7dV54bWA.png)

**Get the app’s Client ID** that google created for you. Copy the client ID. You will need it in further steps of this guide.

![](https://cdn-images-1.medium.com/max/2000/1*sI38TkCWmLHqdU6uTbaiNQ.png)

### Configure the social login module

Use your google client ID and activate the social login module in the providers section of the app.module.ts:

{% gist https://gist.github.com/Chriz76/d4474838f689435a2aa0b894850bf32b %}

The code above also adds the HttpClient module, which will be needed later in this guide.

*Further reading: [Google authentication in Angular](https://medium.com/@danilrabizo/google-authentication-in-the-angular-application-e86df69be58a)*

### Create the Login Code

Edit app.component.ts

{% gist https://gist.github.com/Chriz76/b8efd84f48e37f3263cf9e1fd4cf50dc %}


Edit app.component.html

{% gist https://gist.github.com/Chriz76/c3dc2e040ee8cf0b1b080e13f31a4fab %}


### (Optional) Test the login

Start the app

    c:\dev>ng serve

Open the app URL in your browser, click “Sign in with google” to open the login dialogue. **Sign in with your google credentials**:

![](https://cdn-images-1.medium.com/max/2000/1*m3im9xKxiLzwBfZVtvylvw.png)

**You are now logged in:**

![](https://cdn-images-1.medium.com/max/2000/1*mRr-WNh6KJ5ftHmV41-A0A.png)

**Use the debugger of the [chrome browser](https://www.google.com/intl/de_de/chrome/) to get the idToken** and other information:

![](https://cdn-images-1.medium.com/max/2252/1*9AuoqTfjLmbZzRwxxPpVnA.png)

Google creates a new idToken on every login. The token is only valid for a short time.

Copy the idToken. You will need it in the next step of this guide if you want to manually test the API.

_______________


## 3. Authentication API in the .NET Core Backend

The authentication API will use the idToken from google and verify it. Then it creates an access token that grants access to the other APIs of your app.

> You will have to increase security before you run this code in a production environment: Shorter token lifetime and refreshs, maybe use sessions instead of tokens, etc.

**Install [Visual Studio Community](https://visualstudio.microsoft.com/en/vs/community/)** (it’s free) with the ASP.NET and web development workload. Create an ASP.NET Core Web API project.

### Verification of the idToken

Use the Visual Studio package manager to **install the google Auth Package**:
`Install-Package Google.Apis.Auth`

**Create an API to verify the idToken**.

**Change the value in `settings.Audience` to your google client ID**, that you created in the first step of this guide:

{% gist https://gist.github.com/Chriz76/cacec657e02d670b2dc82d3e8c6f45dc %}


The call to `GoogleJsonWebSignature.ValidateAsync` will throw in case of an error. The `Authenticate` method uses the `JwtGeneratorclass` to create and return a custom access token.

### Create Custom Access Tokens in .NET Core Using Asymmetric Signatures

With asymmetric JWT signing, only the authentication service knows the private key. The authentication service uses the private key to sign the access token and other APIs use only the public key to verify the access token.

**Add the `JwtGenerator` class**, that generates the token:

{% gist https://gist.github.com/Chriz76/4adca6d3df876d75ecd4ba88094063c6 %}


The JwtGenerator uses the private key, that it gets passed from the UserController. **Add the key to appsettings.json**, where the UserControler reads it from.

{% gist https://gist.github.com/Chriz76/a101713cd8526d068e23d86f42b3932c %}


You can use my private key for testing but you will have to create your own private-public key pair for production use. You will also have to adjust token lifetime, etc. for production use.

*Further reading: [JWT Authentication with Asymmetric Encryption using certificates in ASP.NET Core](https://edstefanescu.medium.com/jwt-authentication-with-asymmetric-encryption-using-certificates-in-asp-net-core-7790d3ce499). *This story also shows how to create your own public-private key pair.

**Edit Startup.cs**, which configures the ASP.NET Core backend to use the config, allow access from the Angular client, etc.:

{% gist https://gist.github.com/Chriz76/61d7b4e210cff71dd94e8e118f3f5fb1 %}


_______________


## 4. Use the Authentication API

Configure the .NET Core API project in debug mode on HTTPS port 5001:

![](https://cdn-images-1.medium.com/max/2000/1*b8RHjI1538Ph71TCZnPNdw.png)

Start the authentication API in Visual Studio:

![](https://cdn-images-1.medium.com/max/2000/1*xJn_cUjtOKamk61z2UJ0sA.png)

### (Optional) Manually access the authentication API

Use [postman](https://www.postman.com/downloads/) to access the API at: `https://localhost:5001/user/authenticate`

Post the idToken, that you copied from the Chrome debugger in the second step of this guide:

![](https://cdn-images-1.medium.com/max/2768/1*T_2Eh_o78-c9lDZ2tbeFtQ.png)

### Call the authentication API from the app

Use the Angular HttpClient to post the idToken to the authentication API. **Modify app.component.ts**:

* Line 5: Import the HttpClient

* Lines 21: Send the idToken

{% gist https://gist.github.com/Chriz76/5f23b6e0d784cffa877b139a82a53b42 %}


### (Optional) Test the workflow in the app

Do the same as in the first step of this guide.

Start the app

    c:\dev>ng serve

Login and use the debugger and logging in the chrome browser to verify that calling the backend and receiving the generated access token is working:

![](https://cdn-images-1.medium.com/max/2330/1*GfKqVFpDML6BbdOyQ2VyCg.png)

Copy the access token if you want to do a manual test in the next step of this guide.

_______________


## 5. Use the Access Token to Call the Service API

The access token from the authentication API will grant access to this new service API.

**Create an ASP.NET Core Web API project** and configure it in debug mode on HTTPS port 5002:

![](https://cdn-images-1.medium.com/max/2000/1*TS8EN5S9_bjIrruOav8-tw.png)

**Add a controller:**

{% gist https://gist.github.com/Chriz76/75c25b42ca62d08ea6fe038d95d0e250 %}


**Edit Startup.cs**. It took me a while to configure the validation of the token. The public key to the corresponding private key of the authentication API is used to validate the token. The hard part was to inject the public key. See the comments in the source code for details:

{% gist https://gist.github.com/Chriz76/ddb51f316a4b9483a9287371944492ab %}


### (Optional) Use postman to access the service API

Use [postman](https://www.postman.com/downloads/) to access the service API via HTTP GET at: `https://localhost:5002/secured`

In the previous part of this guide, you copied the access token in the Chrome debugger. **Add it as bearer token to the call**:

![](https://cdn-images-1.medium.com/max/2090/1*VbGeA5MIS2ou-zttKw_jPQ.png)

### The Final step of this guide: Use the app to access the service API

**Modify app.component.ts** to post the access key to the service API:

{% gist https://gist.github.com/Chriz76/bf7aac68e023d29e0e9e98961f98a34a %}


**You successfully accessed the protected service API:**

![](https://cdn-images-1.medium.com/max/2000/1*uX4I0zm1oHsm1ea-w10ufA.png)

_______________


## 6. Final Thoughts and Outlook

**Your app is now fully working!** But it is only a sample application and you will have to **clean up the code** and **apply security best practices**, maybe use a more secure OAuth flow, use Angular and .NET Core design patterns, error handling, etc. to use it in production. And you need your own private-public key pair ([see JWT Authentication with Asymmetric Encryption using certificates in ASP.NET Core](https://edstefanescu.medium.com/jwt-authentication-with-asymmetric-encryption-using-certificates-in-asp-net-core-7790d3ce499) by 
Eduard Stefanescu).

You can **add other providers** like facebook or your own account database. 
See also my **follow-up stories**:
* [How to use NSwag to autogenerate the TypeScript client](https://dev.to/christianzink/how-to-jwt-authenticate-with-angular-to-an-asp-net-core-api-openapi-swagger-using-nswag-typescript-54fl) to access the .NET Core service API and use OpenAPI/Swagger to describe the API
* [How to deploy the .NET Core API and Angular App as Microservices to Kubernetes using Ingress and develop local using Docker Desktop](https://dev.to/christianzink/how-to-build-an-asp-net-core-kubernetes-microservices-architecture-with-angular-on-local-docker-desktop-using-ingress-395n)


**Please contact me if you have any questions, ideas, or suggestions.**