简体   繁体   English

Firebase Auth setCustomClaims() 不起作用

[英]Firebase Auth setCustomClaims() not working

I am facing a problem with setting custom claims for Firebase Authentication service's token.我在为 Firebase 身份验证服务的令牌设置自定义声明时遇到问题。 I am using Cloud function to set the custom claims for Hasura.我正在使用 Cloud function 为 Hasura 设置自定义声明。 The cloud function executes upon new user create event to set the custom claims.云 function 在新用户创建事件时执行以设置自定义声明。 Here's my code running in cloud function这是我在云中运行的代码 function

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp();

exports.processSignup = functions.auth.user().onCreate(user => {
    // create custom claims for hasura
    const hasuraClaims = {
        "x-hasura-default-role": "user",
        "x-hasura-allowed-roles": ["user"],
        "x-hasura-user-id": user.uid
    }

    // attach claims to user auth object
    return admin.auth().setCustomUserClaims(user.uid, hasuraClaims)
        .then(_ => {
            functions.logger.info('SUCCESS: Custom claims attached');
        })
        .catch(err => {
            console.log('ERROR: ', err);
        })
})

In my frontend web page, I am running the following code to get the idToken在我的前端 web 页面中,我正在运行以下代码来获取idToken

// subscribe to user state change
firebase.auth().onAuthStateChanged(async user => {
    console.log('Firebase auth state changed');

    if (user) {
        // User is signed in.
        window.User = user;

        let idToken = await user.getIdTokenResult();
        console.log('idToken: ', idToken);
    }
})

I don't know what I'm doing wrong, but the token doesn't contain the custom claims that I've set in my Cloud function processSignup() .我不知道我做错了什么,但令牌不包含我在 Cloud function processSignup()中设置的自定义声明。 I know that the function executed without error because I can check my function logs and find the info entry SUCCESS: Custom claims attached .我知道 function 执行没有错误,因为我可以检查我的 function 日志并找到信息条目SUCCESS: Custom claims attached claim added 。

Can anyone please help me solve this problem?谁能帮我解决这个问题?

Updating claims does not trigger an onAuthStateChanged (the auth state of being logged in or not has not changed, but the users' claims have) and tokens are minted and then used for ~1h.更新声明不会触发onAuthStateChanged (登录或未登录的身份验证state没有更改,但用户的声明已更改)并且令牌被铸造然后使用约 1 小时。

You are calling getIdTokenResult but not forcing a refresh, try:您正在调用getIdTokenResult但不强制刷新,请尝试:

let idToken = await user.getIdTokenResult(true);

which will force a new token to be fetched from the server and will (hopefully) include your custom claims.这将强制从服务器获取新令牌,并将(希望)包含您的自定义声明。

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

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