如何验证谷歌云功能以访问安全的应用引擎端点

时间:2017-08-20 23:30:54

标签: google-app-engine google-cloud-platform google-cloud-functions google-authentication

Google Cloud Platform引入了身份识别代理,用于保护App Engine灵活环境实例免受公共访问。

但是,如果能够或应该从访问GAE托管API端点的Google云端功能中使用它,目前尚不完全清楚。

documentation(使用Python和Java示例)表示IAP身份验证工作流程,包括1)生成JWT令牌,2)创建OpenID令牌,3)然后使用{{}向Google App Engine提交请求1}}标题。

如果在每次调用函数时都必须进行授权,那么运行云函数似乎很复杂。

Google云端功能是否有另一种方式可以访问安全的GAE端点?

4 个答案:

答案 0 :(得分:6)

如果您想从GCF拨打受IAP保护的应用程序,您确实应该使用ID令牌。在Nodejs中没有示例,所以我使用this作为参考(样式可能是错误的,因为这是我第一次触摸nodejs)。与常规JWT声明集不同,它不应包含范围并具有target_audience。

/**
 * Make IAP request
 *
 */
exports.CfToIAP = function CfToIAP (req, res) {
  var crypto = require('crypto'),
      request = require('request');
  var token_URL = "https://www.googleapis.com/oauth2/v4/token";
  // service account private key (copied from service_account.json)
  var key = "-----BEGIN PRIVATE KEY-----\nMIIEvQexsQ1DBNe12345GRwAZM=\n-----END PRIVATE KEY-----\n";

  // craft JWT
  var JWT_header = new Buffer(JSON.stringify({ alg: "RS256", typ: "JWT" })).toString('base64');
  // prepare claims set
  var iss = "12345@12345.iam.gserviceaccount.com";  // service account email address (copied from service_account.json)
  var aud = "https://www.googleapis.com/oauth2/v4/token";
  var iat = Math.floor(new Date().getTime() / 1000);
  var exp = iat + 120; // no need for a long linved token since it's not cached
  var target_audience = "12345.apps.googleusercontent.com"; // this is the IAP client ID that can be obtained by clicking 3 dots -> Edit OAuth Client in IAP configuration page
  var claims = {
    iss: iss,
    aud: aud,
    iat: iat,
    exp: exp,
    target_audience: target_audience
  };
  var JWT_claimset = new Buffer(JSON.stringify(claims)).toString('base64');
  // concatenate header and claimset
  var unsignedJWT = [JWT_header, JWT_claimset].join('.');
  // sign JWT
  var JWT_signature = crypto.createSign('RSA-SHA256').update(unsignedJWT).sign(key, 'base64');
  var signedJWT = [unsignedJWT, JWT_signature].join('.');
  // get id_token and make IAP request
  request.post({url:token_URL, form: {grant_type:'urn:ietf:params:oauth:grant-type:jwt-bearer', assertion:signedJWT}}, function(err,res,body){
    var data = JSON.parse(body);
    var bearer = ['Bearer', data.id_token].join(' ');
    var options = {
      url: 'https://1234.appspot.com/', // IAP protected GAE app
      headers: {
        'User-Agent': 'cf2IAP',
        'Authorization': bearer
      }
    };
    request(options, function (err, res, body) {
      console.log('error:', err);
    });
  });
  res.send('done');
};

/**
 * package.json
 *
 */

{
  "name": "IAP-test",
  "version": "0.0.1",
  "dependencies": {
    "request": ">=2.83"
  }
}

更新:不建议使用捆绑服务帐户密钥,因此更好的选择是使用元数据服务器。要使以下示例正常工作,应启用Google身份和访问管理(IAM)API,并且App Engine默认服务帐户应具有服务帐户角色(默认编辑器不够):

/**
 * Make request from CF to a GAE app behind IAP:
 * 1) get access token from the metadata server.
 * 2) prepare JWT and use IAM APIs projects.serviceAccounts.signBlob method to avoid bundling service account key.
 * 3) 'exchange' JWT for ID token.
 * 4) make request with ID token.
 *
 */
exports.CfToIAP = function CfToIAP (req, res) {
  // imports and constants
  const request = require('request');
  const user_agent = '<user_agent_to_identify_your_CF_call>';
  const token_URL = "https://www.googleapis.com/oauth2/v4/token";
  const project_id = '<project_ID_where_CF_is_deployed>';
  const service_account = [project_id,
                           '@appspot.gserviceaccount.com'].join(''); // app default service account for CF project
  const target_audience = '<IAP_client_ID>';
  const IAP_GAE_app = '<IAP_protected_GAE_app_URL>';

  // prepare request options and make metadata server access token request
  var meta_req_opts = {
    url: ['http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/',
          service_account,
          '/token'].join(''),
    headers: {
      'User-Agent': user_agent,
      'Metadata-Flavor': 'Google'
    }
  };
  request(meta_req_opts, function (err, res, body) {
    // get access token from response
    var meta_resp_data = JSON.parse(body);
    var access_token = meta_resp_data.access_token;

    // prepare JWT that is {Base64url encoded header}.{Base64url encoded claim set}.{Base64url encoded signature}
    // https://developers.google.com/identity/protocols/OAuth2ServiceAccount for more info
    var JWT_header = new Buffer(JSON.stringify({ alg: "RS256", typ: "JWT" })).toString('base64');
    var iat = Math.floor(new Date().getTime() / 1000);
    // prepare claims set and base64 encode it
    var claims = {
      iss: service_account,
      aud: token_URL,
      iat: iat,
      exp: iat + 60, // no need for a long lived token since it's not cached
      target_audience: target_audience
    };
    var JWT_claimset = new Buffer(JSON.stringify(claims)).toString('base64');

    // concatenate JWT header and claims set and get signature usign IAM APIs projects.serviceAccounts.signBlob method
    var to_sign = [JWT_header, JWT_claimset].join('.');    
    // sign JWT using IAM APIs projects.serviceAccounts.signBlob method
    var signature_req_opts = {
      url: ['https://iam.googleapis.com/v1/projects/',
            project_id,
            '/serviceAccounts/',
            service_account,
            ':signBlob'].join(''),
      method: "POST",
      json: {
        "bytesToSign": new Buffer(to_sign).toString('base64')
      },
      headers: {
        'User-Agent': user_agent,
        'Authorization': ['Bearer', access_token].join(' ')
      }
    };
    request(signature_req_opts, function (err, res, body) {
      // get signature from response and form JWT
      var JWT_signature = body.signature;
      var JWT = [JWT_header, JWT_claimset, JWT_signature].join('.');

      // obtain ID token
      request.post({url:token_URL, form: {grant_type:'urn:ietf:params:oauth:grant-type:jwt-bearer', assertion:JWT}}, function(err, res, body){
        // use ID token to make a request to the IAP protected GAE app
        var ID_token_resp_data = JSON.parse(body);
        var ID_token = ID_token_resp_data.id_token;
        var IAP_req_opts = {
          url: IAP_GAE_app,
          headers: {
            'User-Agent': user_agent,
            'Authorization': ['Bearer', ID_token].join(' ')
          }
        };
        request(IAP_req_opts, function (err, res, body) {
          console.log('error:', err);
        });
      });
    });
  });
  res.send('done');
};

答案 1 :(得分:2)

对于仍在关注2020年及以后的任何人,Google都使这变得非常容易。

他们的docs举例说明了如何认证在Cloud Functions中运行良好的IAP:

// const url = 'https://some.iap.url';
// const targetAudience = 'IAP_CLIENT_ID.apps.googleusercontent.com';

const {GoogleAuth} = require('google-auth-library');
const auth = new GoogleAuth();

async function request() {
  console.info(`request IAP ${url} with target audience ${targetAudience}`);
  const client = await auth.getIdTokenClient(targetAudience);
  const res = await client.request({url});
  console.info(res.data);
}

答案 2 :(得分:0)

正如本doc中所述,您可以使用以下方式对Google Cloud Platform(GCP)API进行身份验证:

1-服务帐户(首选方法) - 使用与您的GCP项目相关联的Google帐户,而不是特定用户。

2-用户帐户 - 当应用程序需要代表最终用户访问资源时使用。

3- API密钥 - 通常在调用不需要访问私有数据的API时使用。

答案 3 :(得分:0)

有些人使用Google云端口密钥管理服务(KMS)来避免在云端功能中对其进行硬编码。

https://cloud.google.com/kms/