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の使い方を調べつつ書いてみました。
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の使えてない機能がいっぱいあるので試していきたいです。