Struggling with the Transition from Google Sign-In

Having difficulty transitioning from Google Sign-In.

"{error: 'idpiframe_initialization_failed', details: 'You have created a new client application that use…i/web/guides/gis-migration) for more information.'}"

How do I update the authentication code and gapi commands in order to integrate with the newer version? Grateful for any assistance in understanding!

index.html snippet:

<head>
  <meta name = "google-signin-client-id" content ="XXXX.googleusercontent.com
  ">
  <script src="https://apis.google.com/js/api.js"></script>


</head>
<body>
  <div class="g-signin2" data-onsuccess ="onSignIn" data-longtitle="true"></div>

  <app-root></app-root>
</body>

google-signin.service.ts excerpt:

import { Injectable } from '@angular/core';
import {Observable, ReplaySubject} from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class GoogleSigninService {

  private auth2: gapi.auth2.GoogleAuth
  private subject = new ReplaySubject<gapi.auth2.GoogleUser> (1)

  constructor() { 
    gapi.load('auth2', () => {
member (the above private auth2)
      this.auth2 = gapi.auth2.init({
        client_id: 'XXXXXX....apps.googleusercontent.com'
      })
    })
  }
  public signIn(){
    this.auth2.signIn({
      scope: 'https://www.googleapis.com/auth/gmail.readonly'
    }).then (user => {
      this.subject.next(user)
    }).catch( () => {
      this.subject.next(null)
    }) 
  }
  public signOut(){
    this.auth2.signOut()
      .then( () => {
        this.subject.next(null)
      })
  }
  public observable(): Observable <gapi.auth2.GoogleUser>{
    return this.subject.asObservable()
  }
}

app.component.ts portion:

import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import {Router, NavigationEnd} from '@angular/router';
import { GoogleSigninService } from './google-signin.service';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  title = 'google-signin';
  user: gapi.auth2.GoogleUser;

  constructor(private signInService: GoogleSigninService, private ref: ChangeDetectorRef , private dialog: MatDialog, private router: Router) {}
  companySwipe(): void {
    this.router.navigateByUrl('/companyswipe');
  }

  ngOnInit(): void {
    this.signInService.observable().subscribe(user => {
      this.user = user
      this.ref.detectChanges()
    })
  }

  signIn (){
    this.signInService.signIn()
  }

  signOut(){
    this.signInService.signOut()
  }
}

tsconfig.app.json:

  "compilerOptions": {
    "types": ["jest", "gapi", "gapi.auth2"]
  },

app.component.html section:

<button (click) ="signIn()" *ngIf = "user == null"> GOOGLE SIGNIN</button>
<button (click) = "signOut()" *ngIf = "user  != null" > GOOGLE SIGNOUT</button>
<div *ngIf ="user != null">
  <div> You are signed in with Google! {{user.getBasicProfile().getName()}} </div>
</div>

Answer №1

Make sure to add the Google Identity Service library to your head tag:

<script src="https://accounts.google.com/gsi/client"></script>

Don't forget to install the types:

npm install --save-dev @types/google.accounts

In your service, initialize the client like this:

this.tokenClient = google.accounts.oauth2.initTokenClient({
  client_id: "YOUR_GOOGLE_CLIENT_ID",
  scope: "THE_REQUESTED_SCOPES",
  prompt: "SELECT_A_PROMPT_OPTION", // '' | 'none' | 'consent' | 'select_account'
  callback: this.handleCredentialResponse // function to handle the response post-login. You will receive an 'access_token' in the response
});

After signing in, you will receive a response with an 'access_token'. Remember to store it in local storage.

To sign in, simply call requestAccessToken on the tokenClient:

this.tokenClient.requestAccessToken(overrideConfig) // initiate the prompt 

You can use overrideConfig for additional options, refer to the types declaration file for more details

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for accessing data in Angular 2

When utilizing the post method, the following code is used in the ts file: viewt(testid) { $('#myModal22').modal('show'); var param2 = { testid:testid, } this.service.get_tquestion(param2).subscribe(data => { ...

Error in Angular: trying to access property 'genre' of an undefined object

I am currently developing a simple app inspired by a tour of heroes (official angular tutorial). However, I have encountered an issue that I cannot seem to resolve, possibly due to my lack of understanding in basic programming concepts. Here is the code s ...

Error encountered during compilation while attempting to import a JSON file in Angular 7

One great aspect of angular 7 is its compatibility with typescript 3.1: https://alligator.io/angular/angular-7/ I have made the following changes to the tsconfig.json file, within the 'compilerOptions' section: "resolveJsonModule": true, "esMo ...

Ionic 6 prioritizes enhanced accessibility by implementing toast blocks that divert attention away from input fields

Scenario: My form is basic, but when the user tries to submit it with invalid inputs, I show a toast message with an error. Issue: Since upgrading to Ionic 6, I noticed that while the error toast is visible, I am unable to focus on any input fields until ...

How can I select just one element to be impacted by a click event when using map in TypeScript?

Currently, I'm facing an issue where I want to change the icon of a button when it's selected. The problem is that using map affects all buttons even if only one is selected. // ... const [clicked, setClicked] = useState(false); <Button sta ...

Reconnect automatically SignalR client upon server restart

I am currently using ASP.NET Core SignalR within the ASP.NET Boilerplate project, and everything runs smoothly while the server is running. However, whenever I need to restart the server for any reason, I encounter these errors: https://i.sstatic.net/Thr ...

Issues with incorrect source path in Typescript, Gulp, and Sourcemaps configuration

In my nodejs app, the folder structure is as follows: project |-- src/ | |-- controllers/ | | |`-- authorize-controller.ts | |`-- index.ts |--dist/ | |--controllers/ | | |`-- authorize-controller.js | | |`-- authorize-controller.js.map | ...

Encountering build errors in .xproj file when working with Type Script in ASP.Net Core

I recently started working on a new ASP.Net Core project and decided to integrate Angular 2 and Type Script by following a blog post tutorial. However, upon adding a Type Script file to my project, I encountered several build errors from the xproj file. h ...

Combining Keycloak with Azure B2C for identity management and implementing the authorization code flow

My current challenge involves integrating Keycloak with Azure B2C using authorization code flow. I have my Keycloak instance deployed as an Azure App Service, along with an Azure B2C tenant and a demo SPA app that I am attempting to authenticate through Az ...

Update the value in a nested object array by cross-referencing it with a second nested object array and inserting the object into the specified

I have a large array of objects with over 10,000 records. Each object contains an array in a specific key value, which needs to be iterated and compared with another array of objects. If there is a match, I want to replace that value with the corresponding ...

Don't forget to include the line 'import "reflect-metadata"' at the beginning of your entry point for Jest tests

As I work on developing an application using dependency injection with tsyringe, I came across a case where a service receives the repository as a dependency. Here is an example: import { injectable, inject } from 'tsyringe' import IAuthorsRepos ...

TypeScript version 3.7 has implemented a new feature where it will now display errors for each individual invalid prop instead of grouping them together as it

Scenario using TypeScript 3.5.3 https://i.stack.imgur.com/wykd6.png link to interactive playground - TS 3.5.3 demo running successfully Example with TypeScript 3.7.2 https://i.stack.imgur.com/BPckB.png link to demo - TS 3.7.2 demo not functioning correctl ...

Tips for providing certificate key file during the deployment of a cloud function?

Within my TypeScript file, the following code is present: import * as admin from 'firebase-admin' import * as functions from 'firebase-functions' const serviceAccountKey = "serviceAccountKey.json" const databaseURL = "https://blahblah. ...

Validate prop must consist of one of two functional components

I am looking to ensure that a prop can only be one of two different components. Here is what I currently have: MyComponent.propTypes { propA: PropTypes.oneOfType([ PropTypes.instanceOf(ClassComponentA) PropTypes.instanceOf(ClassCompon ...

In TypeScript, how to refer to the type of the current class

Is there a way to reference the current class type in the type signature? This would allow me to implement something like the following: export class Component{ constructor(config?: { [field in keyof self]: any }) { Object.assign(this, config) ...

Angular Reactive Forms may not properly update other inputs when binding a control to multiple inputs

While working with reactive forms, I encountered an issue where accessing the same control in multiple inputs seemed to result in one-way data binding (input-to-model). If I make edits in one input, it updates the model correctly but does not refresh the o ...

Struggling to grasp how to implement Redux and React-router together in one component

I have recently embarked on learning TypeScript and encountered a confusing behavior. Upon encountering this error: Type 'ComponentClass<{}>' is not assignable to type 'StatelessComponent<void | RouteComponentProps<any>> ...

The Angular Syncfusion schedule is unable to call upon an object that may potentially be 'undefined'

Currently, I am developing an application using Angular Syncfusion to allow users to view and book appointments. I found a helpful resource at the following link: Below you can find the code snippet I have been working on: <ejs-schedule #scheduleObj ...

Updating Form Array Values in AngularLearn how to efficiently update values within a form

I am currently utilizing Angular8 and reactive forms. Here is my ngOnInit function: ngOnInit(): void { this.makeForm = this.fb.group( year: ['', Validators.required], amount: ['', Validators.required], desc: ['', ...

Encountering a validation error when attempting to submit the form

I am facing an issue with my form. Inside the form, I have a dropdown menu that dynamically displays a textbox upon selection. The form also includes an array feature to allow for multiple textboxes to be displayed. Despite filling in all fields with value ...