Using Google user data

We can now focus on incorporating a Google login in our LoginPanelComponent. First up, we need to set a click handler for the Login with Google button as follows:

<button class="btn btn-primary"
    (click)="onLoginGoogleClicked()">Login with Google</button>  

Here, we have updated our login-panel.component.html file and linked the function named onLoginGoogleClicked to the click event on our form. We can then update our component itself as follows:

constructor(
    private userService: UserService, 
    private router: Router, 
    private socialAuthService: AuthService) { }
    
    onLoginGoogleClicked() {
        this.socialAuthService.signIn(GoogleLoginProvider.PROVIDER_ID)
          .then((userdata) => {
    
            this.userService.authenticateGoogleUser(userdata)
                .subscribe((response: any) => {
                localStorage.setItem('token', response);
                this.router.navigate([``]);
            }, (err) => {
                console.log(`onLoginClicked() : error : 
${JSON.stringify(err, null, 4)}`); this.error = `${err.message}`; }); }).catch((error) => { console.log(`error : ${error}`); }); }

Here, we have included a private constructor variable named socialAuthService that will be set to the instance of the AuthService by Angular's dependency injection framework. We then define the onLoginGoogleClicked function that uses this AuthService to call the signIn function with the correct PROVIDER_ID for Google. Note that this call returns a Promise, so we have defined both a .then handler for a successful response, and a .catch handler in case of an error.

When the Google authentication service returns with a success response, it will provide us with a JSON structure that includes information related to the logged-in user. We then pass this user data into a new function on our UserService that will POST to a new endpoint in order to generate a locally signed JWT token. Once we have a signed token, we can store it in Local Storage, and redirect the user to the SecureComponent.

The implementation of the authenticateGoogleUser is a simple HttpClient POST method in the UserService in order to send the user data to our Express server as follows:

authenticateGoogleUser(data: any) { 
    const headers = new HttpHeaders(); 
    headers.append('Content-Type', 'application/json'); 
 
    return this.httpClient.post(
'/login-google', data,
{ 'headers': headers }); }

This function simply constructs a POST to the Express endpoint named /login-google, and sends the user data as the JSON body. We can implement the route handler in the Express server userRoutes.ts file as follows:

router.post(`/login-google`, (req: any, res: any, next: any) => { 
    serverLog(`POST /login-google`); 
    if (req.body.name & req.body.name.length > 0) { 
 
        let user_context = { 
            username: req.body.name 
        } 
 
        var token = jwt.sign(user_context, jwtSecret); 
        res.json(token); 
 
    } else { 
        serverLog(`/login-google - Error : Invalid google token`); 
        res.status(401).send('Invalid google token');} 
 
}); 

Here, we have defined a POST handler for the endpoint named /login-google. This handler just checks that the name property of the JSON data that was posted is valid. If so, it constructs an Object named user_context that contains a single property named username, and sets its value to the value of the name property. As we did with the /login route handler, we create a JWT token, and sign it using the sign function of the jwt library, passing in our server secret. We then return this token to the caller of the REST endpoint.

So what have we accomplished in relation to an external authentication service such as Google? The steps that we have worked through are as follows:

  1. Install the angular-6-social-login-v2 library.
  2. Register our application with Google and obtain a Client ID and Client Secret.
  3. Update the app.module.ts file to configure and register the AuthServiceConfig provider.
  4. Create a click handler event for when a user clicks on the Login with Google button.
  5. Call the signIn function of the AuthService instance in order to authenticate our user with Google, and return a JSON user data structure.
  6. POST this user data structure to our Express server using an Angular service.
  7. Generate a JWT token that is signed by our Express server.
  8. Store this JWT token in Local Storage so that the AuthGuard can allow the user to navigate to the SecureComponent.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.21.5