Firebase Admin SDK: Set / Merge Custom User Claims

巧了我就是萌 提交于 2019-12-10 23:54:55

问题


Does Firebase have any trick like { merge: true } to set extra/more custom claims without delete/override the old variables?

Step to reproduce:

admin.auth().setCustomUserClaims(uid, { a: 'value' }) // Run this first
admin.auth().setCustomUserClaims(uid, { b: 'value' }) // Then run this after

Result:

{ b: 'value'}

Expected result:

{ a: 'value', b: 'value' }

Or I did something wrong?


回答1:


The Firebase documentation for setCustomUserClaims states:

  • customUserClaims: Object
    The developer claims to set. If null is passed, existing custom claims are deleted. Passing a custom claims payload larger than 1000 bytes will throw an error. Custom claims are added to the user's ID token which is transmitted on every authenticated request. For profile non-access related user attributes, use database or other separate storage systems.

It isn't entirely clear from this description, but the statement, "If null is passed, existing custom claims are deleted," provides a hint that the custom claims are completely overwritten with each call to setCustomUserClaims.

Therefore, custom claims need to be set as follows:

claims = {
  a: 'value',
  b: 'value'
}

admin.auth().setCustomUserClaims(uid, claims) 

Workaround: addCustomUserClaims

A helper function could be created to merge in new claims.

async function addCustomUserClaims(uid, claims) {
  const user = await admin.auth().getUser(uid)
  let updated_claims = user.customClaims || {}

  for (let property in claims) {
    if (Object.prototype.hasOwnProperty.call(claims, property)) {
      updated_claims[property] = claims[property]
    }
  }
  await admin.auth().setCustomUserClaims(uid, updated_claims)
}


来源:https://stackoverflow.com/questions/57429120/firebase-admin-sdk-set-merge-custom-user-claims

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!