Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Firebase custom user claims are not set without wasting too much if your time.
The question is published on by Tutorial Guruji team.
The question is published on by Tutorial Guruji team.
I am trying to add custom user claims after user sign up, to define user role, using setCustomUserClaims:
/api/users/addUser.js
export default async (req, res) => { const { displayName, email, password, role } = req.body; if (!displayName || !password || !email || !role) { return res.status(400).send({ message: 'Missing fields' }); } try { const { uid } = await admin.auth().createUser({ displayName, email, password, }); await admin.auth().setCustomUserClaims(uid, role); res.status(201).send(uid); } catch (error) { handleError(res, error); } };
This code checks for any change in the authentication state and sets user to the currently logged in user:
/utils/use-auth.js
useEffect(() => { const unsubscribe = firebase.auth().onAuthStateChanged((user) => { if (user) { setUser(user); } else { setUser(false); // Router.push('/login'); } });
in my /pages/user/home,jsx:
import { useAuth } from '../../utils/use-auth'; function home() { const { user } = useAuth(); return ( <div> <pre>{JSON.stringify(user, null, 4)}</pre> <AdminLayout componentProps={{ selected: '1' }} Component={HomeContent} /> </div> ); }
The displayed object doesn’t have any custom claims. when I check the firebase console, I find that the user is actually added.
Answer
Try using
admin.auth().setCustomUserClaims(uid, claims).then(() => { // Do your stuff here });
And verify the claims like
admin.auth().verifyIdToken(idToken).then((claims) => { // check claims if (claims) { // do your stuff here } });
for more info check https://firebase.google.com/docs/auth/admin/custom-claims#node.js
We are here to answer your question about Firebase custom user claims are not set - If you find the proper solution, please don't forgot to share this with your team members.