LoginSignup
4
2

More than 3 years have passed since last update.

Auth0でログインユーザーのロール(Roles)を元にハンドリングするRulesを書いてみた

Last updated at Posted at 2020-01-07

Auth0でログインしたユーザーによって処理を変えたいときに、Rulesというログイン時に任意スクリプトを実行してハンドリングさせる機能があります。

参考: 「Auth0」のRulesが便利機能だった!! / 『「Auth0」で作る!認証付きシングルページアプリケーション』でAuth0をさわってみた

今回は、 ユーザーのロールを元にハンドリングをする処理を書いてみます

このRulesはNode.jsで記述するFaaS的なものになっているので、公式サンプルには無いものも比較的カスタマイズしやすそうです。

例: whitelist - 特定のメールアドレスの人を通す

公式サンプルです。こんな雰囲気。

function (user, context, callback) {

  // Access should only be granted to verified users.
  if (!user.email || !user.email_verified) {
    return callback(new UnauthorizedError('Access denied.'));
  }

  const whitelist = [ 'user1@example.com', 'user2@example.com' ]; //authorized users
  const userHasAccess = whitelist.some(
    function (email) {
      return email === user.email;
    });

  if (!userHasAccess) {
    return callback(new UnauthorizedError('Access denied.'));
  }

  callback(null, user, context);
}

ユーザーのロールを元に判定

ここで、ユーザーのロールを見て、特定のロールの人は通して、それ以外は除外するといった処理を追加してみます。

HTTPモジュールのRequestが利用できるのでRequestの使い方を調べつつ書いてみました。

参考: Node.jsのrequestモジュールを使ってHTTPSでPOSTリクエストを行う

Enpty Rulesを選んで以下をコピペで使えると思います。

また、settingsの箇所でtokenなどの値を設定することができます。
RulesのNode.js側からはconfiguration.キー名って形で取得できます。

キャプチャだとtokenというキー名にしたのでconfiguration.tokenでNode.js側で呼び出せます。

function (user, context, callback) {
  console.log(context, user, user.identities[0].access_token);
  // Access should only be granted to verified users.
  if (!user.email || !user.email_verified) {
    return callback(new UnauthorizedError('Access denied.'));
  }

  const token = configuration.token; //Auth0のAPIのアクセストークン (Settingsで指定したもの)
  const options = {
    url: `https://xxxxxx.auth0.com/api/v2/users/${user.user_id}/roles`,
    method: 'GET',
    headers: {
        'Authorization': `Bearer ${token}`
        },
    json: true,
  };
  request(options, (err, response, body) => {
    //許可するロール名    
    const whiteList = ['role1','role2'];
    const userRoles = body.map(item => item.name);
    const userHasAccess = userRoles.some(value => whiteList.includes(value));

    if (!userHasAccess) {
      return callback(new UnauthorizedError('Access denied.'));
    }

    callback(null, user, context);
  });
}

ホワイトリストの配列のチェックをさせてますが、.some()便利ですね。

所感

Node.jsなので割と色々と任意の処理をさせることができそうですね。

Rules内でnpm上の外部モジュールは使えるのかとか色々気になります。

個人的にはaxiosが使えると便利なんだけどなぁと思いつつまた次回にしたいと思います。

まだまだAuth0の使えてない機能がいっぱいあるので試していきたいです。

4
2
3

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
4
2