Implementing Google Sign-In in an Angular application allows users to authenticate using their Google accounts, providing a seamless and secure login experience. Below is a comprehensive, step-by-step guide to integrating Google Sign-In using the latestGoogle Identity Services (GIS) library.
Table of Contents
- Prerequisites
- Create a Google Cloud Project and Configure OAuth Consent
- Install Required Dependencies
- Add Google Identity Services Script
- Create a Google Sign-In Component
- Handle Authentication
- Protect Routes (Optional)
- Logout Functionality
- Security Considerations
- Conclusion
Prerequisites
Before you begin, ensure you have the following:
- Angular CLI installed. If not, install it using:
npminstall-g @angular/cli
- Node.js and npm installed on your machine.
- AGoogle account to access Google Cloud Console.
1. Create a Google Cloud Project and Configure OAuth Consent
- Create a New Project:
- Go to theGoogle Cloud Console.
- Click on the project dropdown and selectNew Project.
- Enter aProject Name and clickCreate.
- Configure OAuth Consent Screen:
- Navigate toAPIs & Services >OAuth consent screen.
- ChooseExternal for the user type and clickCreate.
- Fill in theApp name,User support email, and other required fields.
- AddScopes as needed (for basic sign-in, default scopes are sufficient).
- AddTest Users if you're using an external user type.
- Save and continue through the steps until completion.
- Create OAuth 2.0 Client ID:
- Go toAPIs & Services >Credentials.
- ClickCreate Credentials >OAuth client ID.
- SelectWeb application as the application type.
- Enter aName (e.g., "Angular App").
- InAuthorized JavaScript origins, add your development and production URLs, e.g.,
http://localhost:4200
andhttps://yourdomain.com
. - InAuthorized redirect URIs, add the redirect URI if needed (for GIS, it might not be necessary).
- ClickCreate and note down theClient ID.
2. Install Required Dependencies
For this implementation, we'll use the Google Identity Services (GIS) library directly without additional Angular-specific packages.
Optionally, you can install@types/google.accounts
for TypeScript support.
npminstall--save @types/google.accounts
Note: If@types/google.accounts
is not available, you can declare the types manually.
3. Add Google Identity Services Script
You need to include the GIS library in your Angular application. The recommended way is to add the script in theindex.html
.
Open
src/index.html
.Add the following script tag inside the
<head>
section:
<scriptsrc="https://accounts.google.com/gsi/client"asyncdefer></script>
<!DOCTYPE html><htmllang="en"><head><metacharset="utf-8"/><title>YourApp</title><basehref="/"/><metaname="viewport"content="width=device-width, initial-scale=1"/><linkrel="icon"type="image/x-icon"href="favicon.ico"/><scriptsrc="https://accounts.google.com/gsi/client"asyncdefer></script></head><body><app-root></app-root></body></html>
4. Create a Google Sign-In Component
Create a dedicated component for handling Google Sign-In.
- Generate a new component:
ng generate component google-sign-in
- Implement the Component:
Opensrc/app/google-sign-in/google-sign-in.component.ts
and update it as follows:
import{Component,OnInit,NgZone}from'@angular/core';declareconstgoogle:any;@Component({selector:'app-google-sign-in',templateUrl:'./google-sign-in.component.html',styleUrls:['./google-sign-in.component.css']})exportclassGoogleSignInComponentimplementsOnInit{constructor(privatengZone:NgZone){}ngOnInit():void{this.initializeGoogleSignIn();}initializeGoogleSignIn(){google.accounts.id.initialize({client_id:'YOUR_GOOGLE_CLIENT_ID',callback:(response:any)=>this.handleCredentialResponse(response)});google.accounts.id.renderButton(document.getElementById('google-signin-button'),{theme:'outline',size:'large'}// customization attributes);google.accounts.id.prompt();// also display the One Tap dialog}handleCredentialResponse(response:any){// response.credential is the JWT tokenconsole.log('Encoded JWT ID token:'+response.credential);// You can decode the JWT token here or send it to your backend for verification// For demonstration, we'll just log it// If using NgZone, ensure any UI updates are run inside Angular's zonethis.ngZone.run(()=>{// Update your application state here, e.g., store user info, navigate, etc.});}}
Important:
- Replace
'YOUR_GOOGLE_CLIENT_ID'
with the Client ID obtained from the Google Cloud Console. handleCredentialResponse
will receive a credential (JWT) that you can verify on your backend.
- Update the Component Template:
Opensrc/app/google-sign-in/google-sign-in.component.html
and add a container for the Google Sign-In button:
<divid="google-signin-button"></div>
You can style or position this div as needed.
- Add the Component to Your App:
For example, include it inapp.component.html
:
<app-google-sign-in></app-google-sign-in>
5. Handle Authentication
After the user signs in, you'll receive a JWT (JSON Web Token) in thehandleCredentialResponse
callback. You need to:
- Decode the JWT (Optional Client-Side):
For security reasons, it's recommended to verify the token on the server. However, if you need to decode it client-side:
npminstalljwt-decode
importjwt_decodefrom'jwt-decode';handleCredentialResponse(response:any){consttoken=response.credential;constdecoded:any=jwt_decode(token);console.log(decoded);// Extract user informationconstuser={name:decoded.name,email:decoded.email,picture:decoded.picture,// ... other fields};// Handle user data as needed}
- Verify the Token on the Backend:
It's crucial to send the token to your backend server for verification to ensure its validity and to prevent security issues.
Example (assuming you have a backend API endpoint):
import{HttpClient}from'@angular/common/http';constructor(privatengZone:NgZone,privatehttp:HttpClient){}handleCredentialResponse(response:any){consttoken=response.credential;// Send the token to your backend for verificationthis.http.post('https://your-backend.com/api/auth/google',{token}).subscribe({next:(res)=>{// Handle successful authentication},error:(err)=>{// Handle errors}});}
Backend Verification:
On your server, use Google's libraries to verify the token's integrity. For example, in Node.js:
const{OAuth2Client}=require('google-auth-library');constclient=newOAuth2Client(CLIENT_ID);asyncfunctionverify(token){constticket=awaitclient.verifyIdToken({idToken:token,audience:CLIENT_ID,});constpayload=ticket.getPayload();constuserid=payload['sub'];// If request specified a G Suite domain:// const domain = payload['hd'];returnpayload;}
6. Protect Routes (Optional)
To protect certain routes in your Angular application and ensure that only authenticated users can access them, you can implement route guards.
- Create an Auth Service:
Generate a service to manage authentication state.
ng generate service auth
// src/app/auth.service.tsimport{Injectable}from'@angular/core';import{BehaviorSubject}from'rxjs';@Injectable({providedIn:'root'})exportclassAuthService{privateauthState=newBehaviorSubject<boolean>(false);authState$=this.authState.asObservable();constructor(){}setAuthState(state:boolean){this.authState.next(state);}isAuthenticated():boolean{returnthis.authState.value;}}
- Update Auth Service on Sign-In:
In yourGoogleSignInComponent
, inject and use theAuthService
:
import{AuthService}from'../auth.service';constructor(privatengZone:NgZone,privateauthService:AuthService){}handleCredentialResponse(response:any){// After successful verification with backendthis.ngZone.run(()=>{this.authService.setAuthState(true);// Navigate to a protected route, e.g.,// this.router.navigate(['/dashboard']);});}
- Create an Auth Guard:
ng generate guard auth
// src/app/auth.guard.tsimport{Injectable}from'@angular/core';import{CanActivate,ActivatedRouteSnapshot,RouterStateSnapshot,UrlTree,Router}from'@angular/router';import{Observable}from'rxjs';import{AuthService}from'./auth.service';@Injectable({providedIn:'root'})exportclassAuthGuardimplementsCanActivate{constructor(privateauthService:AuthService,privaterouter:Router){}canActivate(route:ActivatedRouteSnapshot,state:RouterStateSnapshot):Observable<boolean|UrlTree>|Promise<boolean|UrlTree>|boolean|UrlTree{if(this.authService.isAuthenticated()){returntrue;}else{this.router.navigate(['/login']);returnfalse;}}}
- Protect Routes:
In your routing module, apply the guard to routes that require authentication.
// src/app/app-routing.module.tsimport{NgModule}from'@angular/core';import{RouterModule,Routes}from'@angular/router';import{DashboardComponent}from'./dashboard/dashboard.component';import{LoginComponent}from'./login/login.component';import{AuthGuard}from'./auth.guard';constroutes:Routes=[{path:'login',component:LoginComponent},{path:'dashboard',component:DashboardComponent,canActivate:[AuthGuard]},{path:'',redirectTo:'/login',pathMatch:'full'},// ... other routes];@NgModule({imports:[RouterModule.forRoot(routes)],exports:[RouterModule]})exportclassAppRoutingModule{}
7. Logout Functionality
To allow users to log out, you need to clear their authentication state and optionally revoke the token.
- Add a Logout Method in Auth Service:
// src/app/auth.service.tslogout(){this.authState.next(false);// Optionally, revoke the tokengoogle.accounts.id.disableAutoSelect();// Remove tokens from storage if stored}
- Create a Logout Button:
In your component (e.g.,DashboardComponent
), add a logout button.
<button(click)="logout()">Logout</button>
// src/app/dashboard/dashboard.component.tsimport{Component}from'@angular/core';import{AuthService}from'../auth.service';import{Router}from'@angular/router';@Component({selector:'app-dashboard',templateUrl:'./dashboard.component.html',styleUrls:['./dashboard.component.css']})exportclassDashboardComponent{constructor(privateauthService:AuthService,privaterouter:Router){}logout(){this.authService.logout();this.router.navigate(['/login']);}}
8. Security Considerations
Token Verification: Always verify the ID token on your backend server to ensure its integrity and to prevent malicious logins.
HTTPS: Ensure your application is served over HTTPS, especially in production, as OAuth 2.0 requires secure contexts.
Scopes: Request only the necessary scopes needed for your application to minimize privacy concerns.
Token Storage: Avoid storing tokens in localStorage or sessionStorage to prevent XSS attacks. Consider using HttpOnly cookies for storing tokens if possible.
9. Conclusion
Integrating Google Sign-In into your Angular application enhances user experience by providing a quick and secure authentication method. By following the steps outlined above, you can implement Google Sign-In using the latest Google Identity Services library, ensuring your application adheres to current best practices and security standards.
Remember to handle tokens securely and verify them on your backend to maintain the integrity and security of your authentication flow. Additionally, always keep your dependencies updated and monitor Google's documentation for any changes or updates to their authentication services.
If you encounter any issues or need further customization, refer to theGoogle Identity Services documentation for more detailed information and advanced configurations.
Top comments(2)

- WorkSoftware Developer at Afrosoft Holdings
- Joined
Thank you, this helped alot.

- Email
- LocationLagos, Nigeria
- EducationFederal University of Technology, Owerri
- PronounsHe/Him
- WorkFounder/CEO, Bloomnet Digital Technologies Limited
- Joined
I'm glad it helped. I have yet another approach. I will write about it soon.
For further actions, you may consider blocking this person and/orreporting abuse