【发布时间】:2020-06-28 15:06:58
【问题描述】:
我正在为应用使用 Firebase 身份验证,但作为用户创建的一部分,我需要设置一些自定义声明。
我编写了一个云函数来在创建用户时设置声明:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
// On sign up.
exports.processSignUp = functions.auth.user().onCreate(user => {
let customClaims;
// Set custom user claims on this newly created user.
return admin.auth().setCustomUserClaims(user.uid, {
'https://hasura.io/jwt/claims': {
'x-hasura-default-role': 'user',
'x-hasura-allowed-roles': ['user'],
'x-hasura-user-id': user.uid
}
})
.then(() => {
// Update real-time database to notify client to force refresh.
const metadataRef = admin.database().ref("metadata/" + user.uid);
// Set the refresh time to the current UTC timestamp.
// This will be captured on the client to force a token refresh.
return metadataRef.set({
refreshTime: new Date().getTime()
});
})
.then(() => {
return admin.auth().getUser(user.uid);
})
.then(userRecord => {
console.log(userRecord);
return userRecord.toJSON();
})
.catch(error => {
console.log(error);
});
});
当我将 userRecord 打印到控制台时,我可以看到自定义声明设置正确。
然后在颤振中我从创建的用户那里获得令牌,但它似乎没有附加自定义声明。
我正在使用此代码创建用户并在 Flutter 中打印声明
Future<FirebaseUser> signUp({String email, String password}) async {
final FirebaseUser user = (await auth.createUserWithEmailAndPassword(
email: email,
password: password,
)).user;
IdTokenResult result = await (user.getIdToken(refresh: true));
print('claims : ${result.claims}');
return user;
}
如果我在 jwt 调试器中检查令牌本身,我可以看到它没有得到自定义声明。
设置声明后,我是否需要一些额外的步骤来尝试获取更新的令牌?
我试过 user.reload() 和 user.getIdToken(refresh: true) 但它们似乎没有帮助。
关于如何获取具有自定义声明的令牌的任何想法?
【问题讨论】:
-
我通过调用 AuthResult result = await auth.signInWithEmailAndPassword(email: email, password: password);在获得索赔之前意味着我确实获得了自定义索赔。使用电子邮件和密码登录时这很好,但我不知道在使用其他身份验证提供商(例如 google/facebook)登录时我会如何做。
标签: flutter firebase-authentication jwt google-cloud-functions jwt-auth