简体   繁体   中英

Any API to add an authorized domain to Firebase Auth?

Just want to check, is there any API to add the authorized domain in a programmatical way instead of adding it manually by going to Firebase console?

Also, is there any limit on how many domains can be added as the authorized domains?

JavaScript in Cloud Functions solution

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,
      ],
    }),
  });
})();

A quick note on other languages

The principles should be the same:

  • Find a way to interact with Google's identify toolkit API (maybe Google offers an SDK to your language)
  • Get current config
  • Set new config

If you can't find an SDK, you can also work with raw http requests: https://cloud.google.com/identity-platform/docs/reference/rest/v2/projects/getConfig (it's just a bit trickier to do authentication when doing everything manually)

There is no API for this - you must do it through the console. You can also file a feature request with Firebase support if you want.

There doesn't appear to be any documentation stating limits of number of domains. Again, reach out to Firebase support if the documentation is unclear.

Thanks @Jean Costa

Totally working for me.

Here is C# implementation

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
    }
}

Thanks @Jean Costa and @Yan Naing

here is my php implemetation

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM