Я не получаю access_token при использовании Google oauth

#javascript #vue.js #google-oauth #amazon-cognito

#javascript #vue.js #google-oauth #amazon-cognito

Вопрос:

Это настройка из идентификатора клиента Google для веб-приложения:

введите описание изображения здесь

Этот код работает:

     <html lang="en">
  <title>| COGNITO-IDP-AUTH |</title>
  <head>
    <meta name="author" content="sebolabs">
    <meta name="google-signin-scope" content="profile email">
    <!-- Google Client ID -->
    <meta name="google-signin-client_id" content="622988289048-55555lkgs1jlrstvehfq9ur333ksio.apps.googleusercontent.com">
    <script src="https://apis.google.com/js/platform.js" async defer></script>
    <script src="https://sdk.amazonaws.com/js/aws-sdk-2.2.19.min.js"></script>
    <script src="scripts.js"></script>
  </head>
  <body>
    <div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div>
    <p />
    <button onclick="onSignOut()">Sign out</button>
    <p />
    <div id="output"></div>
  </body>
</html>
 

И scripts.js:

 function onSignIn(googleUser) {
  // profile info
  var profile = googleUser.getBasicProfile();
  console.log('Full Name: '   profile.getName());
  console.log('Email: '   profile.getEmail());
  // auth response
  console.log('Google authentication response:');
  var authResponse = googleUser.getAuthResponse()
  console.log(authResponse);
  var id_token = authResponse.id_token;
  console.log('JWT token (encrypted): '   id_token);
  console.log('JWT token (decrypted):');
  console.log(parseJwt(id_token));
  signInCallback(authResponse);
}

function signInCallback(authResult) {
  if (authResult['access_token']) {
    
    // adding google access token to Cognito credentials login map
    AWS.config.region = 'us-west-2';
    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
      IdentityPoolId: 'us-west-2:757555de-06b6-4131-a82c-001df33286d9',
      Logins: {
        'accounts.google.com': authResult['id_token']
      }
    });

    // obtain credentials
    AWS.config.credentials.get(function(err) {
      if (!err) {
        console.log('Cognito Identity Id: '   AWS.config.credentials.identityId);
      } else {
        document.getElementById('output').innerHTML = "<b>YOU ARE NOT AUTHORISED TO QUERY AWS!</b>";
        console.log('ERROR: '   err);
      }
    });

  } else {
    console.log('User not logged in!');
  }
}

function parseJwt(token) {
  var base64Url = token.split('.')[1];
  var base64 = base64Url.replace('-', ' ').replace('_', '/');
  var plain_token = JSON.parse(window.atob(base64));
  return plain_token;
}

function onSignOut() {
  var auth2 = gapi.auth2.getAuthInstance();
  auth2.signOut().then(function () {
    console.log('User signed out.');
  });
  AWS.config.credentials.clearCachedId();
  document.getElementById('output').innerHTML = "";
}
 

Но когда я добавил это в свой проект, я не получаю access_token:

Этот код выше: введите описание изображения здесь

Это мой код: введите описание изображения здесь

Мой код в Vue.JS:

 <!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <!-- Google Client ID -->
    <meta name="google-signin-client_id" content="622988289048-55555lkgs1jlrstvehfq9ur333ksio.apps.googleusercontent.com">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title><%= htmlWebpackPlugin.options.title %></title>

    <script src="https://apis.google.com/js/platform.js" async defer></script>
  </head>
  <body>
    <noscript>
      <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>


<template>
  <div>
    <h2>Login page</h2>
    <router-link to="/">Return to home</router-link>
  </div>
  <div>
    <div id="google-signin-btn"></div>
    <p/>
    <button v-on:click="onSignOut">Sign out</button>
    <p/>
    <div id="output"></div>
  </div>
</template>
<script>
import AWS from 'aws-sdk';

export default {

  methods: {
    onSignIn(googleUser) {
      // profile info
      let profile = googleUser.getBasicProfile();
      console.log('Full Name: '   profile.getName());
      console.log('Email: '   profile.getEmail());
      // auth response
      console.log('Google authentication response:');
      let authResponse = googleUser.getAuthResponse()
      console.log(authResponse);
      let id_token = authResponse.id_token;
      console.log('JWT token (encrypted): '   id_token);
      console.log('JWT token (decrypted):');
      console.log(this.parseJwt(id_token));
      this.signInCallback(authResponse);
    },
    signInCallback(authResult) {
      if (authResult['access_token']) {

        // adding google access token to Cognito credentials login map
        AWS.config.region = 'us-west-2';
        AWS.config.credentials = new AWS.CognitoIdentityCredentials({
          IdentityPoolId: 'us-west-2:7572d6de-06b6-4131-a82c-001df33286d9',
          Logins: {
            'accounts.google.com': authResult['id_token']
          }
        });

        // obtain credentials
        AWS.config.credentials.get(function (err) {
          if (!err) {
            console.log('Cognito Identity Id: '   AWS.config.credentials.identityId);
          } else {
            document.getElementById('output').innerHTML = "<b>YOU ARE NOT AUTHORISED TO QUERY AWS!</b>";
            console.log('ERROR: '   err);
          }
        });

      } else {
        console.log('User not logged in!');
        document.getElementById('output').innerHTML = "<b>YOU ARE NOT AUTHORISED TO QUERY GOOGLE!</b>";
      }
    },
    parseJwt(token) {
      let base64Url = token.split('.')[1];
      let base64 = base64Url.replace('-', ' ').replace('_', '/');
      let plain_token = JSON.parse(window.atob(base64));
      return plain_token;
    },
    onSignOut() {
      let auth2 = gapi.auth2.getAuthInstance();
      auth2.signOut().then(function () {
        console.log('User signed out.');
      });
      AWS.config.credentials.clearCachedId();
      document.getElementById('output').innerHTML = "";
    }
  },
  mounted() {
    gapi.signin2.render('google-signin-btn', { // this is the button "id"
      onsuccess: this.onSignIn // note, no "()" here
    })
  }
}
</script>
 

Почему я не получаю access_token???

Похоже, что ваш пост в основном состоит из кода; пожалуйста, добавьте еще несколько деталей. Похоже, что ваш пост в основном состоит из кода; пожалуйста, добавьте еще несколько деталей. Похоже, что ваш пост в основном состоит из кода; пожалуйста, добавьте еще несколько деталей.

Комментарии:

1. Вы используете Google sigin для аутентификации в этом open id connect, вы получаете id_token, токены доступа предназначены для Oauth2 и предназначены для авторизации.

2. Почему я в первом случае получаю access_token, а во втором нет?

3. Я решил это сам, я забыл добавить это: <meta name=»google-signin-scope» content=»profile email»> в моем index.html