LoginSignup
14
6

More than 3 years have passed since last update.

Firebaseのカスタムクレームについて

Last updated at Posted at 2020-12-11

こんにちは、M2のmarutakuです。これはMYJLab Advent Calendar 2020の11日目の記事です。前回は、@nyaxによる超簡単!Youtubeの動画をpytubeでダウンロードでした。
今日の記事は、過去に自分が良かったなと思ったFirebaseの便利機能である、カスタムクレームについてです。

カスタムクレームとは

カスタムクレーム(Custom Claim)は、Firebase Authenticationで持っているユーザ情報に対して、独自の属性を付与するための機能です。
https://firebase.google.com/docs/auth/admin/custom-claims

具体的な用例としては、以下のようなものが考えられます。

  • 有料会員と無料会員の区別
  • サービスの管理者権限を与える
  • ユーザが所属するグループを分ける

カスタムクレームのメリット、デメリット

  • メリット
    • セキュリティルールの中で使用できる
    • ユーザによる書き換えの心配がない
  • デメリット
    • Firebase Adminからしか操作できない
    • 1000バイト以上のデータは保持できない

使い方

const admin = require('firebase-admin');
admin.initializeApp();

...

// uidはfirebase authenticationから提供されるuid
await admin.auth().setCustomUserClaims(uid, { role: 'teacher' });

これだけで、カスタムクレームがセットできました。
クライアント側でカスタムクレームを参照するときはこのように参照します。

const tokenResult = await firebase.auth().currentUser.getIdTokenResult();
if (tokenResult.claims.role === 'teacher'){
    // 教員向けの処理
} else {
    // 学生向けの処理
}

簡単!!!

注意点

カスタムクレームは複数のkey-valueを持つことができますが、一部のkey-valueのみを更新することはできません。
例:

const auth = admin.auth();
// 1回目
await auth.setCustomUserClaims(uid, { 
    role: 'teacher' 
});

// 二回目
await auth.setCustomUserClaims(uid, { 
    admin: true 
});

// 確認
const user = await auth.getUser(uid);
console.log(user.claims['role']); // undefined
console.log(user.claims['admin']); // true

一部の値のみを更新したい場合でも、全ての値を含めて更新をする必要があります。

const user = await auth.getUser(uid);
await auth.setCustomUserClaims(uid, { 
    ...user.claims,
    admin: true 
});

終わりに

またあっさりとした記事になってしまいましたが、結構便利機能なので機会があればぜひ使ってみてもらいたいです!

14
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
6