Acquire the id_token from Google using oauth2

I am currently working with AngularJS on the client side and trying to implement Google OAuth2. While I have successfully obtained the access token, I now need to retrieve the ID token.

In order to achieve this, I have made modifications in app.js, controller.js, and the HTML section.

For guidance, I referred to the tutorial available at:

Here is a snippet from app.js:

 angular
  .module('angularoauthexampleApp', [ ])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
      })
      .when('/access_token=:accessToken', {
        template: '',
        controller: function ($location,$rootScope) {
          var hash = $location.path().substr(1);

          var splitted = hash.split('&');
          var params = {};

          for (var i = 0; i < splitted.length; i++) {
            var param  = splitted[i].split('=');
            var key    = param[0];
            var value  = param[1];
            params[key] = value;
            $rootScope.accesstoken=params;
          }
          $location.path("/about");
        }
      })
      .otherwise({
        redirectTo: '/'
      });
  });

Snippet from controller.js:

angular.module('angularoauthexampleApp')
  .controller('MainCtrl', function ($scope) {

    $scope.login=function() {
        var client_id="your client_id";
        var scope="email";
        var redirect_uri="http://localhost:9000";
        var response_type="token";
        var url="https://accounts.google.com/o/oauth2/auth?scope="+scope+"&client_id="+client_id+"&redirect_uri="+redirect_uri+
        "&response_type="+response_type;
        window.location.replace(url);
    };
  });

HTML section:

<button class="btn btn-primary" ng-click="login()">Login</button>

Answer №1

To obtain the id_token in your response, you must incorporate a nonce.

Here's an example:

let params = {
    'client_id': GOOGLE_API_CLIEND_ID,
    'redirect_uri': `${location.origin}/auth/google`,
    'response_type': 'id_token token',
    'scope': GOOGLE_API_SCOPES,
    'state': 'af0ifjsldkj',
    'nonce': 'n-0S6_WzA2Mj'
};

The nonce parameter is essential for the implicit flow. For more details, refer to

Answer №2

If you want to obtain an id_token, simply update your response_type parameter to:

var response_type="id_token";

This will result in receiving just the id_token. If you require both the id_token and access_token, include "token" in the response_type value like this:

var response_type="token id_token";

For further information, refer to the OpenId article

You can also test the authentication flow using the Google Ouath Playground

Answer №3

To initiate an OpenID Connect process, an extension of OAuth 2.0, it is essential to include the "openid" scope in the authorization request (and encode the space between), as shown below:

var scopes="openid%20profile";

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

What is the best way to retrieve information from a database using JSON with PHP, JQUERY, and

Trying to retrieve data from a MySQL database and pass it to a JavaScript file has been quite a challenge. Despite searching extensively online, the examples I found didn't work in my specific scenario. .html file <!DOCTYPE html PUBLIC '-//W ...

Regular expressions tailored for a precise format in JavaScript

Is it possible to create a regex that can validate a specific format? For example, if I have version numbers like v1.0 or v2.0 v1.0 or v2.0 My current regex expression only validates the existence of v, a number, or a .. How can I implement validation ...

Using AngularJS, you can pass serialized objects as query string parameters

I'm trying to pass nested objects as query parameters from my AngularJS Controller using the following code: $scope.redirect = function () { const params = $httpParamSerializer({ initval: { user: { id: 1, ...

Error message: The function send() cannot be applied to the object received by request.post() in Node

As I embark on testing the functionalities of my node.js website using chai and mocha, I encountered an issue when running npm test. The error message displayed is: ' TypeError: request.post(...).send is not a function' Referencing the code sni ...

Searching for the index of a nested array in jQuery using JSON

I am currently working on developing an image uploader using Codeigniter3 along with jQuery and Ajax. Problem: I am facing difficulty in understanding how to locate the index of the array received from the ajax response shown below. Here is the data retu ...

Angular JS is failing to update views when passing dynamic IDs

I have implemented a method in my controller where I pass a dynamic id using the ng-init function, fetch a response through ajax calls, and try to print the response. However, I am facing an issue as the response is not getting printed. I am using ng-repea ...

Seeking clarification on how to load an angular directive

I am puzzled by the fact that in the given jsFiddle, 'here is a log' gets printed three times. http://jsfiddle.net/wg385a1h/5/ $scope.getLog = function () { console.log('here is a log'); } Could anyone shed some light on why thi ...

Increase the value of $index within the ng-repeat loop

Is there a way to increment the value of $index in ng-repeat by a specific amount? For example, if I want to display two values at a time, how can I ensure that the next iteration starts with the third value instead of the second value? <div ng-contr ...

Challenge with modal dialog scrolling on iPad and iPhone

Our website contains various pages that open JQuery 'Modal Dialog' boxes. These modal dialog boxes function well in all web browsers. However, there is an issue when viewing the website on an iPad or iPhone, which seems to be a common problem. ...

Login and session management for users using AngularJS in the client-side and Spring in the backend

Currently, my mobile website is built using angularjs, and the backend is powered by Spring Boot. The issue I am facing is that when a user logs in successfully, their information is obtained from the server, but if they click "back" or "refresh" on the br ...

How to use jQuery to remove the last element from an array when the back button

Currently encountering an issue with removing the last element from an array when a back button is clicked. The console is displaying the correct elements in the array, but it seems that the array.slice function is not working as expected, and I'm str ...

What is the best way to display the unique $index for an array retrieved from Firebase?

I am currently facing an issue. Everything is progressing smoothly. I am using ngRepeat to display lists that are Arrays from Firebase using the $asArray() function. In addition, I am applying a "reverse" filter so that new items appear at the top. Now ...

The name of the controller is not properly registered while loading the HTML via the template

Currently in the process of transitioning my web app from routing through MVC to a Single Page Application (SPA) setup, where all different components are loaded within a single main page. To achieve this, I am utilizing the ngview directive. Below is the ...

Unable to access parameters from Pug template when using onclick event

I am facing an issue with my pug template test.pug. It contains a button that, when clicked, should call a function using parameters passed to the template from the rendering endpoint. Below is the structure of my template: doctype html html head tit ...

Encountered an issue when attempting to create meanjs using yo

After installing yeoman globally, I encountered an error while trying to generate meanjs with yo. Unfortunately, I was unable to identify the root cause of the problem. view image here Any help would be greatly appreciated. I attempted using sudo as well ...

Directive's isolated scope is not functioning as anticipated

I have created a custom directive and you can find the code here: http://jsbin.com/xosusozipufe/1/ The behavior of this directive is not meeting my expectations. I expected the h4 within the directive div to display 'within the app Hello World' ...

Decode a chunked binary response using the Fetch API

Is there a way to properly handle binary chunked responses when using the Fetch API? I have implemented the code below which successfully reads the chunked response from the server. However, I am encountering issues with the data being encoded/decoded in a ...

Error in Node.js React: Unable to add context property as the object is not extendible

Currently, I'm in the process of integrating an isomorphic react component into my node.js + express setup. However, as I attempt to add the component to my jade template for rendering, I encounter this error: TypeError: Can't add property contex ...

Storing formatted user input in an array with VueJS: A step-by-step guide

Looking for assistance that relates to the following question Vue.js: Input formatting using computed property is not applying when typing quick I am facing a challenge in extracting formatted values from text inputs and storing them in an array. I intend ...

Retrieve data from a text file using ajax and then return the string to an HTML document

Just starting out with ajax, I have a text file containing number values For example, in ids.txt, 12345 maps to 54321 12345,54321 23456,65432 34567,76543 45678,87654 56789,98765 Here is the Html code snippet I am using <html><body> < ...