Implementing OAuth2 Login in Angular 17 with Google Cloud Client ID Integration
Hello there!
Welcome to this article where we’ll explore how to supercharge your Angular 17 application using OAuth 2.0 and Google Cloud Client IDs. By integrating these powerful tools, you can provide a perfect and secure authentication experience for your users. Additionally, this integration will allow users to easily authenticate in your application using their Google credentials.
Introduction.
In today’s world, authentication and login are key aspects in web application development. As a developer, it’s your responsibility to protect your user’s data and ensure that your applications are secure. One way to do this is by using OAuth2, an industry standard authorization protocol that allows users to securely grant access to their resources without sharing their passwords.
Prerequisites.
Before we get started, you will need to have the following installed:
- Node.js and npm.
- Angular CLI.
- A Google Cloud console account.
I have created this tutorial to help you to create and register an account on Google Cloud Console.
Setting up project’s components.
We need to create at least the next components and service:
- Login component: Were we have the login button.
- Dashboard component: Component where we will be redirected in case of a successful logging.
- Service component: where OAuth library will be implemented.
This is an idea of how the project’s structure would look like:
Optional: install Angular material.
Angular Material is a UI component library for Angular applications that follows the Material Design guidelines.
ng add @angular/material
Setting up OAuth library.
Oauth2-oidc is an industry standard protocol used for authorization. This package is an Angular library that provides support for OAuth2 and OpenID Connect (OIDC) authentication and authorization in Angular applications.
npm i angular-oauth2-oidc — save
After the installation is completed, we need to add to the typical imports (like to CommonModule and RouterOutlet) the components recently created, all of them into app.component.ts file:
Additionally, we need to import Oauth2 library, which in this case, we will import it on our app.config.ts file:
Create the project’s routes.
We will use the next routes to navigate inside of project, you should add them into your app.routes.ts file:
At this point, we have created all the necessary structure to make the project work.
Login component: create the login button logic.
This is a minimal example of how to create a login component. In our template, we have to use the next code:
Besides, we need to add a call to our service (named as AuthGoogleService) to implement Google’s auth methods. Our login component will look like the following code:
As we are working with Angular 17, we don’t need to use ‘dependecy injection’ to inject the services that we used to do in the constructor. Angular 17 give us the powerfull of inject() function to replace that.
Auth Google service: create authentication Service.
This service will handle the communication with the OAuth2 provider and store the access token. I will describe each method that I have used to implement the logic.
Here is the service structure:
InitConfiguration method.
This method will be used to set up all the configuration’s parameters of our application:
The object AuthConfig
defines configuration’s options related to authentication:
issuer
specifies the URL of the identity provider. In this case, it is set to'https://accounts.google.com'
, indicating Google as the identity provider.strictDiscoveryDocumentValidation
is a boolean flag that indicates whether strict validation of the discovery document should be performed. The discovery document contains information about the OAuth server’s endpoints and capabilities..clientId
represents the client identifier assigned to your application by the OAuth server. This identifier is used to identify and authenticate your application during the authorization process. This id should be taken of your Google cloud configuration.redirectUri
specifies the URI to which the OAuth server should redirect the user after a successful authentication or authorization process.scope
defines the scope of access requested by the client application. The scope determines what resources and actions the client is allowed to access on behalf of the user.
In addition, we will call the following methods:
Configure(authConfig)
is called, passing theauthConfig
object as a parameter. This method is responsible for configuring the OAuth service with the provided authentication options.SetupAutomaticSilentRefresh()
this method sets up automatic silent refresh of tokens to ensure the session remains active without user interaction.LoadDiscoveryDocumentAndTryLogin()
loads the discovery document from the identity provider and attempts to log in the user automatically.
Please note that the values for issuer
, redirectUri
and scope
are not provided in the given configuration. You need to fill in those values according to your specific OAuth server and application requirements. Also, you need to use your specific clientId
to set up this configuration correctly.
Login/Logout, GetProfile and GetToken methods.
These methods are simpler than initConfiguration. We will use them according to project’s necessities.
Here is the explaination of each method:
- Login():
initImplicitFlow,
this method starts the implicit flow of the OAuth 2.0 authentication process, which redirects the user to the identity provider's login page for authentication. - Logout():
Logout()
is used to log the user out of the application. It performs two actions:
- Calls
revokeTokenAndLogout():
this method revokes the access token and performs the logout process with the identity provider. - Calls
logOut():
this method performs additional cleanup and logout operations specific to the OAuth service.
GetProfile()
retrieves the identity claims of the currently authenticated user. It callsgetIdentityClaims()
method which returns an object containing the user's identity claims, such as username, email, and other profile information.GetToken()
is responsible for retrieving the access token of the currently authenticated user. It calls thegetAccessToken()
which returns the access token as a string.
Dashboard component.
Finally, We will to create dashboard component, this component will be shown after a successful login happen.
We will define our template using the next code:
And we will use the next component class code:
and that’s all!!
Now it’s time for testing.
Testing.
You are able to test the application starting the app with ng serve
command. Click the "Sign in with Google" button. You will be redirected to the Google website to sign in.
After to click on “Sign in with Google”, system shows us the next screen:
Or, if you already has logged with your Google account
After that you log in / choose an account, system shows us the next screen:
Finally, we have logged in using Google credentials.
If you click on LogOut button, system shows you the login screen again.
Conclusion
In this article, we explored how to implement OAuth2 login in Angular 17, integrating with Google Cloud Client ID. OAuth2 provides a secure and convenient way for users to log in to your application using their existing credentials. By following the steps outlined in this article, you can easily implement OAuth2 login in your own Angular projects.
Happy coding, thanks for your attention!
Resources
Disclaimer: code shared in this article is just a basic implementation. Depending on your application, you may need to modify the code to suit your needs.
https://github.com/mariodantemariani/angular-17-login-google
- Angular documentation: https://angular.io/docs
- Google Cloud: https://console.cloud.google.com/
- OAuth2-oidc library: https://www.npmjs.com/package/angular-oauth2-oidc