繁体   English   中英

如何创建 Firebase 身份验证声明?

[英]How to create Firebase Authentication claims?

我正在开发一个需要通过服务器应用程序进行身份验证的 Android 应用程序。 服务器应用程序是使用 Spring 安全性的 Spring 引导应用程序。 服务器应用程序使用自定义身份验证提供程序为用户设置授予权限。

这是我用来检索 idToken 的代码:

    FirebaseToken firebaseToken = null;

    try {
        FirebaseApp app = FirebaseUtil.getFirebaseApp();
        firebaseToken = FirebaseAuth.getInstance(app).verifyIdTokenAsync(authenticationToken.getIdToken()).get();
    } catch ( InterruptedException | ExecutionException | CancellationException e ) {
        throw new AuthenticationServiceException(e.getMessage());
    } 

    return firebaseToken; 

一个我有 Firebase 令牌我可以检索这样的声明:

Map<String, Object> claims = token.getClaims();

然后,我可以遍历声明并创建权限,如下所示:

List<GrantedAuthority> authorities = Lists.newArrayList(); 
authorities.add(new SimpleGrantedAuthority("some_role"));

我不知道如何使用 Firebase 控制台创建声明。 这可能吗? 我怀疑我需要使用 Firebase 数据库,但在 firebase 文档中找不到我要查找的内容。

Firebase 身份验证的自定义声明目前只能通过 Firebase Admin SDK 创建。 创建自定义声明文档中

 // Set admin privilege on the user corresponding to uid. admin.auth().setCustomUserClaims(uid, {admin: true}).then(() => { // The new custom claims will propagate to the user's ID token the // next time a new one is issued. });

允许从控制台创建声明也不是一个坏主意,因此我建议您提交功能请求

您还可以使用 Python 轻松完成以下操作:

auth.set_custom_user_claims(user_id, {"admin":True}, app=None)

如果您一直在 localhost 上使用 Firebase Emulator Suite,您可能已经注意到您可以直接在该控制台中编辑用户以添加自定义声明,例如 {"role":"admin"}。 只需 go 到“身份验证”选项卡,单击特定用户的溢出菜单 select“编辑用户”,然后在文本框中设置自定义声明。

您可能在这里,因为您发现“编辑用户”选项没有出现在生产 Firebase 控制台中,因此您需要弄清楚如何使用代码执行相同的操作。 以下是我使用 Python、服务帐户和 Firebase 管理工具从 Windows 设置自定义声明的步骤。 Linux 或 OSX 上的步骤应该类似。 这假设您已经安装了 python 和 pip 。

  1. 从此处开始下载服务用户的凭据。 您将使用在第 3 步中下载的文件。
https://console.firebase.google.com/project/<your_project>/settings/serviceaccounts/adminsdk
  1. 从终端安装 Python 的 firebase-admin 工具(对于 Linux 或 OSX,您可能需要在此命令前加上 sudo):
pip install firebase-admin
  1. 通过从命令行运行python打开 python 终端并执行以下代码行:
    import firebase_admin
    from firebase_admin import credentials, auth
    cred = credentials.Certificate("c:\\Users\\<path_to_my_credentials_file>.json")
    default_app = firebase_admin.initialize_app(cred)
    user = auth.get_user_by_email('<user_email_address>')
    auth.set_custom_user_claims(user.uid, {'role': 'admin'})

    # Verify the change worked:
    user = auth.get_user_by_email('<user_email_address>')
    print(user.custom_claims)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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