Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Kelly Okere
Kelly Okere

Posted on

     

Google Sign-in with Angular and Node.js

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

  1. Prerequisites
  2. Create a Google Cloud Project and Configure OAuth Consent
  3. Install Required Dependencies
  4. Add Google Identity Services Script
  5. Create a Google Sign-In Component
  6. Handle Authentication
  7. Protect Routes (Optional)
  8. Logout Functionality
  9. Security Considerations
  10. Conclusion

Prerequisites

Before you begin, ensure you have the following:

  • Angular CLI installed. If not, install it using:
  npminstall-g @angular/cli
Enter fullscreen modeExit fullscreen mode
  • 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

  1. Create a New Project:
  • Go to theGoogle Cloud Console.
  • Click on the project dropdown and selectNew Project.
  • Enter aProject Name and clickCreate.
  1. 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.
  1. 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
Enter fullscreen modeExit fullscreen mode

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.

  1. Opensrc/index.html.

  2. Add the following script tag inside the<head> section:

<scriptsrc="https://accounts.google.com/gsi/client"asyncdefer></script>
Enter fullscreen modeExit fullscreen mode
<!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>
Enter fullscreen modeExit fullscreen mode

4. Create a Google Sign-In Component

Create a dedicated component for handling Google Sign-In.

  1. Generate a new component:
   ng generate component google-sign-in
Enter fullscreen modeExit fullscreen mode
  1. 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.});}}
Enter fullscreen modeExit fullscreen mode

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.
  1. 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>
Enter fullscreen modeExit fullscreen mode

You can style or position this div as needed.

  1. Add the Component to Your App:

For example, include it inapp.component.html:

<app-google-sign-in></app-google-sign-in>
Enter fullscreen modeExit fullscreen mode

5. Handle Authentication

After the user signs in, you'll receive a JWT (JSON Web Token) in thehandleCredentialResponse callback. You need to:

  1. 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
Enter fullscreen modeExit fullscreen mode
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}
Enter fullscreen modeExit fullscreen mode
  1. 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}});}
Enter fullscreen modeExit fullscreen mode

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;}
Enter fullscreen modeExit fullscreen mode

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.

  1. Create an Auth Service:

Generate a service to manage authentication state.

   ng generate service auth
Enter fullscreen modeExit fullscreen mode
// 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;}}
Enter fullscreen modeExit fullscreen mode
  1. 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']);});}
Enter fullscreen modeExit fullscreen mode
  1. Create an Auth Guard:
   ng generate guard auth
Enter fullscreen modeExit fullscreen mode
// 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;}}}
Enter fullscreen modeExit fullscreen mode
  1. 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{}
Enter fullscreen modeExit fullscreen mode

7. Logout Functionality

To allow users to log out, you need to clear their authentication state and optionally revoke the token.

  1. 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}
Enter fullscreen modeExit fullscreen mode
  1. Create a Logout Button:

In your component (e.g.,DashboardComponent), add a logout button.

<button(click)="logout()">Logout</button>
Enter fullscreen modeExit fullscreen mode
// 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']);}}
Enter fullscreen modeExit fullscreen mode

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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
galwhocod3z profile image
galwhocod3z
Exploring the digital universe, one line of code at a time. Constantly amazed by how ones and zeros create our pixelated realities. ☕👨‍💻
  • Work
    Software Developer at Afrosoft Holdings
  • Joined

Thank you, this helped alot.

CollapseExpand
 
kellyblaire profile image
Kelly Okere
Software Developer (Full Stack) | Business Intelligence Analyst | IT Business Consultant | Researcher | Tech Enthusiast | Angular Advocate
  • Email
  • Location
    Lagos, Nigeria
  • Education
    Federal University of Technology, Owerri
  • Pronouns
    He/Him
  • Work
    Founder/CEO, Bloomnet Digital Technologies Limited
  • Joined

I'm glad it helped. I have yet another approach. I will write about it soon.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Software Developer (Full Stack) | Business Intelligence Analyst | IT Business Consultant | Researcher | Tech Enthusiast | Angular Advocate
  • Location
    Lagos, Nigeria
  • Education
    Federal University of Technology, Owerri
  • Pronouns
    He/Him
  • Work
    Founder/CEO, Bloomnet Digital Technologies Limited
  • Joined

More fromKelly Okere

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp