在Gmail加载项中获取ID令牌以进行后端服务身份验证 [英] Obtain an id token in the Gmail add-on for a backend service authentication

查看:67
本文介绍了在Gmail加载项中获取ID令牌以进行后端服务身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景
我正在使用Google Apps脚本创建Gmail加载项.通过此插件,我想使用REST服务请求连接到我的后端服务器(非Google服务).该请求必须得到授权.获得授权后,我便可以向该服务器发出请求,以在数据库中接收与该用户关联的数据.我已经在我的Web应用程序中使用Google登录来登录后端服务-在前端,我在授权响​​应中的GoogleUser对象中收到id_token.

问题
通过Gmail插件连接到后端服务时,我需要此id_token登录.但是,我找不到方法来访问令牌.

研究
我认为令牌必须可以通过Apps脚本中的API来使用.
在网络应用中,我使用Google Auth API收到了id_token,如下所示:

The background
I'm using the Google Apps Script to create a Gmail Add-on. Via this plugin, I would like to connect to my backend server (a non-Google service) using a REST service request. The request has to be authorised. When authorised, I could then make requests to that server to receive data associated with that user in the database. I'm already using Google sign-in in my webapp to sign in to the backend service - at the front end, I receive the id_token inside of the GoogleUser object in the authorisation response.

The problem
I need this id_token to log in to my backend service when connecting to it via the Gmail plugin. However, I couldn't find a way how to access the token.

The research
I would assume the token must be available through the API in the Apps Script.
In the webapp, I receive the id_token using the Google Auth API like this:

Promise.resolve(this.auth2.signIn())
        .then((googleUser) => {
            let user_token = googleUser.getAuthResponse().id_token; // this is the id_token I need in the Gmail plugin, too

            // send the id_token to the backend service
            ...
        };

在Google Apps脚本API中,我只能找到OAuth令牌:

In the Google Apps Script API I could only find the OAuth token:

ScriptApp.getOAuthToken();

我假设令牌也可以存储在会话中.Google Apps脚本API包含Session类,并且其本身包含getActiveUser方法,该方法返回User对象.但是,User对象仅包含用户的电子邮件地址,不包含ID令牌(或与此有关的其他任何内容):

I assumed the token could also be stored in the session. The Google Apps Script API contains the Session class and that itself contains the getActiveUser method, which returns the User object. The User object, however, only contains the user's email address, no id token (or anything else for that matter):

Session.getActiveUser().getEmail();


问题
有没有办法获取ID令牌?
我是否选择使用Gmail中已登录用户的数据登录后端服务器的正确方法?


The question(s)
Is there a way to obtain the id token?
Am I choosing the right approach to logging in to the backend server using the data of the signed-in user in the Gmail?

推荐答案

方法1:使用 getIdentityToken()

获取有效用户的OpenID Connect身份令牌:

Method 1: use getIdentityToken()

Gets an OpenID Connect identity token for the effective user:

var idToken = ScriptApp.getIdentityToken();
var body = idToken.split('.')[1];
var decoded = Utilities.newBlob(Utilities.base64Decode(body)).getDataAsString();
var payload = JSON.parse(decoded);
var profileId = payload.sub;
Logger.log('Profile ID: ' + profileId);


方法2:使用Firebase和 getOAuthToken()

从Apps Script的OAuth令牌获取Google ID令牌的步骤:


Method 2: use Firebase and getOAuthToken()

Steps to get Google ID Token from Apps Script's OAuth token:

  1. 为您的Apps脚本项目启用Identity Toolkit API.
  2. 通过 https://console.firebase.google将新的Firebase项目添加到您现有的Google Cloud Platform项目中.com/
  3. 为以下平台创建Firebase应用: Web .
  4. 您将获得配置数据: var firebaseConfig = {apiKey:YOUR_KEY,...} .
  5. https://上为Firebase项目启用Google登录方法console.firebase.google.com/project/PROJECT_ID/authentication/providers .
  6. 使用Apps脚本功能获取当前用户的ID令牌:


function getGoogleIDToken()
{
    // get your configuration from Firebase web app's settings
    var firebaseConfig = {
        apiKey: "***",
        authDomain: "*.firebaseapp.com",
        databaseURL: "https://*.firebaseio.com",
        projectId: "***",
        storageBucket: "***.appspot.com",
        messagingSenderId: "*****",
        appId: "***:web:***"
    };

    var res = UrlFetchApp.fetch('https://identitytoolkit.googleapis.com/v1/accounts:signInWithIdp?key='+firebaseConfig.apiKey, {
        method: 'POST',
        payload: JSON.stringify({
            requestUri: 'https://'+firebaseConfig.authDomain,
            postBody: 'access_token='+ScriptApp.getOAuthToken()+'&providerId=google.com',
            returnSecureToken: true,
            returnIdpCredential: true
        }),
        contentType: 'application/json',
        muteHttpExceptions: true
    });

    var responseData = JSON.parse(res);

    idToken = responseData.idToken;

    Logger.log('Google ID Token: ');
    Logger.log(idToken);

    return idToken;
}

RiëlNotermans

这篇关于在Gmail加载项中获取ID令牌以进行后端服务身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆