You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过REST API更新Firebase Auth的user claims?

实现方案

该需求完全可以实现,你可以直接调用Google Identity Platform的底层REST接口完成自定义用户声明更新,无需依赖Firebase Admin SDK的封装。

核心实现步骤

  • 先为你的CloudRun服务绑定具备Firebase Auth管理权限的服务账号,调用接口时需要携带作用域为https://www.googleapis.com/auth/firebase.auth的OAuth 2.0令牌作为请求授权头
  • 调用POST https://identitytoolkit.googleapis.com/v1/accounts:update接口,请求体传入必填参数即可完成声明更新:
    • localId:待更新用户的UID
    • customAttributes:JSON序列化后的自定义声明字符串,直接传入你之前通过setCustomUserClaims方法设置的声明对象的序列化结果即可

Dart 简单实现示例

你可以结合官方googleapis_auth包获取授权令牌,再通过通用HTTP客户端发起请求,示例代码如下:

import 'package:http/http.dart' as http;
import 'package:googleapis_auth/googleapis_auth.dart' as auth;
import 'dart:convert';

Future<void> updateCustomClaims(String uid, Map<String, dynamic> claims) async {
  // 自动获取CloudRun环境下的服务账号凭证
  var client = await auth.clientViaApplicationDefaultCredentials(
    scopes: ['https://www.googleapis.com/auth/firebase.auth'],
  );

  final url = Uri.parse('https://identitytoolkit.googleapis.com/v1/accounts:update');
  final response = await client.post(
    url,
    body: jsonEncode({
      'localId': uid,
      'customAttributes': jsonEncode(claims),
    }),
  );

  if (response.statusCode != 200) {
    throw Exception('更新声明失败: ${response.body}');
  }
  client.close();
}

注:如果需要更完善的Auth相关操作,也可以使用社区维护的Dart版Firebase Admin包,功能和官方Admin SDK对齐,无需自行封装接口调用逻辑


内容的提问来源于stack exchange,提问作者owlbear

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 03:45:00