有任何 API 可以将授权域添加到 Firebase Auth 中吗?

问题描述 投票:0回答:5

只是想检查一下,是否有任何API可以以编程方式添加授权域,而不是通过Firebase控制台手动添加?

另外,可以添加多少个域名作为授权域名有限制吗?

firebase firebase-authentication
5个回答
10
投票

Cloud Functions 解决方案中的 JavaScript

import { google } from "googleapis";

(async () => {
  /**
   * ! START - Update Firebase allowed domains
   */

  // Change this to whatever you want
  const URL_TO_ADD = "engineering.acme-corp.net";

  // Acquire an auth client, and bind it to all future calls
  const auth = new google.auth.GoogleAuth({
    scopes: ["https://www.googleapis.com/auth/cloud-platform"],
  });
  const authClient = await auth.getClient();
  google.options({ auth: authClient });

  // Get the Identity Toolkit API client
  const idToolkit = google.identitytoolkit("v3").relyingparty;

  /**
   * When calling the methods from the Identity Toolkit API, we are
   * overriding the default target URLs and payloads (that interact
   * with the v3 endpoint) so we can talk to the v2 endpoint, which is
   * what Firebase Console uses.
   */

  // Generate the request URL
  const projectId = await auth.getProjectId();
  const idToolkitConfigUrl = `https://identitytoolkit.googleapis.com/admin/v2/projects/${projectId}/config`;

  // Get current config so we can use it when we later update it
  const currentConfig = await idToolkit.getProjectConfig(undefined, {
    url: idToolkitConfigUrl,
    method: "GET",
  });

  // Update the config based on the values that already exist
  await idToolkit.setProjectConfig(undefined, {
    url: idToolkitConfigUrl,
    method: "PATCH",
    params: { updateMask: "authorizedDomains" },
    body: JSON.stringify({
      authorizedDomains: [
        ...(currentConfig.data.authorizedDomains || []),
        URL_TO_ADD,
      ],
    }),
  });
})();

关于其他语言的快速说明

原理应该是一样的:

  • 找到一种与 Google 的识别工具包 API 交互的方法(也许 Google 为您的语言提供了 SDK)
  • 获取当前配置
  • 设置新配置

如果找不到 SDK,您还可以使用原始 http 请求:https://cloud.google.com/identity-platform/docs/reference/rest/v2/projects/getConfig(这只是一个手动执行所有操作时进行身份验证有点棘手)


2
投票

没有用于此目的的 API - 您必须通过控制台来执行此操作。 如果需要,您还可以向 Firebase 支持人员提出功能请求

似乎没有任何文档说明域数量的限制。 如果文档不清楚,请再次联系 Firebase 支持。


1
投票

谢谢@Jean Costa

完全为我工作。

这是C#实现

using Google.Apis.Auth.OAuth2;
using Newtonsoft.Json;


var serviceAccountJsonFile = "path to service account json";
var projectId = "your project ids";

var authorizedDomains = new
{
    authorizedDomains = new string[] {
        "localhost",
        "******.firebaseapp.com",
        "*********.web.app",
        "abc.def.com"
    }
}; // your desire authorized domain


List<string> scopes = new()
{
    "https://www.googleapis.com/auth/identitytoolkit",
    "https://www.googleapis.com/auth/firebase",
    "https://www.googleapis.com/auth/cloud-platform"
};

var url = "https://identitytoolkit.googleapis.com/admin/v2/projects/" + projectId + "/config";
using var stream = new FileStream(serviceAccountJsonFile, FileMode.Open, FileAccess.Read);
var accessToken = GoogleCredential
        .FromStream(stream) // Loads key file
        .CreateScoped(scopes) // Gathers scopes requested
        .UnderlyingCredential // Gets the credentials
        .GetAccessTokenForRequestAsync().Result; // Gets the Access Token

var body = JsonConvert.SerializeObject(authorizedDomains);
using (var client = new HttpClient())
{
    var request = new HttpRequestMessage(HttpMethod.Patch, url) { 
        Content = new StringContent(body,System.Text.Encoding.UTF8)
    };
    request.Headers.Add("Accept", "application/json");
    request.Headers.Add("Authorization", "Bearer " + accessToken);

    try
    {
        var response = client.SendAsync(request).Result;
        Console.WriteLine(response.Content.ReadAsStringAsync().Result);
    }
    catch (HttpRequestException ex)
    {
        // Failed
    }
}

0
投票

感谢@Jean Costa 和@Yan Naing

这是我的 php 实现

use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Exception\TransferException; 
use Google\Service\IdentityToolkit; 
use Google\Service\IAMCredentials; 

        $KEY_FILE_LOCATION = storage_path('/app/credentials/service-account-1.json') ;

        if (!file_exists($KEY_FILE_LOCATION)) {
            throw new Exception(sprintf('file "%s" does not exist', $KEY_FILE_LOCATION));
        }
    
        $json= file_get_contents($KEY_FILE_LOCATION);

        if (!$config = json_decode($json, true)) {
            throw new Exception('invalid json for auth config');
        }


        $client = new \Google\Client();
        $client->setAuthConfig($config );
        $client->setScopes([ "https://www.googleapis.com/auth/identitytoolkit",
        "https://www.googleapis.com/auth/firebase",
        "https://www.googleapis.com/auth/cloud-platform"]);

        $service =  new IdentityToolkit($client); 
        // Get the Identity Toolkit API client
        $idToolkit =  $service->relyingparty; 
        //Get current config
        $current_config= $idToolkit->getProjectConfig();


        //Get service account access token
        $access_token_req = new IAMCredentials\GenerateAccessTokenRequest();
        $access_token_req->setScope( "https://www.googleapis.com/auth/firebase");
        $credentials = new IAMCredentials($client);
        $access_token = $credentials->projects_serviceAccounts->generateAccessToken("projects/-/serviceAccounts/{$config["client_email"]}" , $access_token_req )->getAccessToken();
        
        // Generate the request URL (https://cloud.google.com/identity-platform/docs/reference/rest/v2/projects/updateConfig)
        $idToolkitConfigUrl = "https://identitytoolkit.googleapis.com/admin/v2/projects/{$config["project_id"]}/config";
          
        $authorized_domains = [  'authorizedDomains' => array_merge(  ['twomore.com'],$current_config->authorizedDomains)];
        
        $client = new GuzzleClient( );
        $response = null;
        try {
            $response  = $client->request('PATCH', $idToolkitConfigUrl,   [
                'verify' =>   Helpers::isProduction() ? true : false  ,
                'http_errors'=> false, //off 4xx and 5xx exceptioins
                'json' =>  $authorized_domains ,
                'headers' => [ 
                    "Authorization" => "Bearer " . $access_token ,
                    "Accept"     => "application/json",   
                 ]
            ]);
        } catch (TransferException $e) {
       
            throw new Exception( $e->getMessage());
        }
       
        $data = json_decode($response->getBody()->getContents(),true);
        
      
        if($response->getStatusCode()!==200){
         
            throw new Exception($response->getReasonPhrase()  . ( isset($data['exception']['message']) ?  " - " . $data['exception']['message'] : ""));
        }

      
        return response()->json(['data' => [

            'authorized_domains' =>  $data['authorizedDomains'] 
        ]]); 


0
投票

Python 版本,假设使用默认凭据:

    from google.auth import default
    from googleapiclient.discovery import build
    from googleapiclient.http import HttpRequest, HttpError
    import json

    URL_TO_ADD = f"totally-new.url"

    
    # Authenticate and construct service
    credentials, project_id = default(scopes=['https://www.googleapis.com/auth/cloud-platform'])
    service = build('identitytoolkit', 'v3', credentials=credentials)
        
    # Generate the request URL
    id_toolkit_config_url = f'https://identitytoolkit.googleapis.com/admin/v2/projects/{project_id}/config?updateMask=authorizedDomains'

    
    # Get current config
    current_config = service.relyingparty().getProjectConfig().execute()
    
    # Update the config based on the values that already exist
    authorized_domains = current_config.get('authorizedDomains', [])
    authorized_domains.append(URL_TO_ADD)
    
    # Create a custom request to update the project config
    http = service._http
    headers = {'Content-Type': 'application/json'}
    body = json.dumps({'authorizedDomains': authorized_domains})

    try:
        response = http.request(
            uri=id_toolkit_config_url,
            method='PATCH',
            headers=headers,
            body=body
        )
    except HttpError as error:
        print(f"An error occurred: {error}")

    # Execute the request
    print(response)
    
    print(f"Added {URL_TO_ADD} to authorized domains.")
    return
© www.soinside.com 2019 - 2024. All rights reserved.