With Auth0 we can define roles and permissions. Permissons have to be added from the Applications/API section, in the Permissions tab, as you can see in this picture:
For roles, you will have to go to the User Management / Roles menu option, where you will be abel to create as many roles as you want. Once you have created a user, you will be able to associate as many permissions as you want to the selected role, to do it, just open the user details and go to the Permissions tab:
In order to get the permissions and roles defined in Auth0, you will have to create a new rule in your Auth0 dashboard. To do it, just go to the Auth Pipeline menu option, click in Rules and add a new rule with the next code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async function(user, context, callback) { | |
const namespace = 'https://yournamespace/identity/claims'; | |
const map = require('array-map'); | |
const ManagementClient = require('auth0@2.17.0').ManagementClient; | |
const management = new ManagementClient({ | |
token: auth0.accessToken, | |
domain: auth0.domain | |
}); | |
const params = { id: user.user_id, page: 0, per_page: 50, include_totals: true }; | |
const permissions = await management.getUserPermissions(params); | |
const assignedPermissions = map(permissions.permissions, function (permission) { | |
return permission.permission_name; | |
}); | |
const assignedRoles = context.authorization ? context.authorization.roles : null; | |
if (context.idToken) { | |
const idTokenClaims = context.idToken; | |
idTokenClaims[`${namespace}/roles`] = assignedRoles ? assignedRoles : ["Guest"]; | |
idTokenClaims[`${namespace}/permissions`] = assignedPermissions; | |
context.idToken = idTokenClaims; | |
} | |
if (context.accessToken) { | |
const accessTokenClaims = context.accessToken; | |
accessTokenClaims[`${namespace}/roles`] = assignedRoles ? assignedRoles : ["Guest"]; | |
accessTokenClaims[`${namespace}/permissions`] = assignedPermissions; | |
context.accessToken = accessTokenClaims; | |
} | |
callback(null, user, context); | |
} |
var roles = principal.Claims.Where(x => x.Type == $"{this.AuthConfiguration.Namespace}/roles")?.Select(x => x.Value).ToList();
var permissions = principal.Claims.Where(x => x.Type == $"{this.AuthConfiguration.Namespace}/permissions")?.Select(x => x.Value).ToList();
Comentarios
Publicar un comentario