是否有任何API可将授权域添加到Firebase Auth?

a9wyjsp7  于 2022-11-30  发布在  其他
关注(0)|答案(4)|浏览(168)

只是想检查一下,是否有任何API以编程方式添加授权域,而不是通过进入Firebase控制台手动添加?
另外,对于可以添加多少个域作为授权域是否有限制?

ee7vknir

ee7vknir1#

云函数解决方案中的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的identify toolkit API交互的方法(也许Google会为您的语言提供SDK)
  • 获取当前配置
  • 设置新配置

如果您找不到SDK,也可以使用原始http请求:https://cloud.google.com/identity-platform/docs/reference/rest/v2/projects/getConfig(手动执行所有操作时,进行身份验证会比较麻烦)

pokxtpni

pokxtpni2#

没有API可以实现这一点--你必须通过控制台来完成。如果你愿意的话,你也可以file a feature request with Firebase support
似乎没有任何文档说明域的数量限制。同样,如果文档不清楚,请联系Firebase支持。

pkmbmrz7

pkmbmrz73#

谢谢@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
    }
}
v09wglhw

v09wglhw4#

感谢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'] 
        ]]);

相关问题