我正在努力将 Microsoft SSO 添加到我的 React 应用程序中。我正在关注我找到的这个教程:https://www.m-sterspace.io/posts/role-auth-azure-react#24-replace-their-authjs-component
我可以正常登录和注销部分。现在我正在想办法如何实现角色。在该教程中,他从最初的
acquireTokenSilent
调用中提取角色。但根据我的研究,我们可能希望将角色存储在应用程序的单独自定义数据库中,因为每个用户可能有多个角色。例如,read:users
和modify:categories
等。我认为Azure AD中不可能有这样的角色。
所以我的问题是如何在初次登录通话时获得这些角色?我想在 React 代码中使用它们来确定用户可以访问哪些页面和不能访问哪些页面。从上面的链接查看 Auth.js 组件,特别是 setSession 函数:
setSession(idToken) {
try {
let roles = [];
// I don't think we can use the roles from Microsoft, we have to get them from our own database
if (idToken.claims.roles) {
roles = idToken.claims.roles;
}
const user = {
id: idToken.objectId,
name: idToken.claims.name,
email: idToken.preferredName || idToken.preferred_username,
role: roles[0]
};
this.setState({
authenticated: true,
idToken: idToken.rawIdToken, //this is the raw token that you want to pass to as your Bearer token.
user: user,
roles: []
});
} catch (e) {
var aux = e.stack.split('\n');
aux.splice(0, 2); //removing the line that we force to generate the error (var err = new Error();) from the message
aux = aux.join('\n"');
console.log(e + ' \n' + aux);
}
}
我猜测我会在顶部的代码块中对我的数据库进行 api 调用,他在其中设置令牌声明中的角色。那行得通吗?那有意义吗?我需要以另一种方式解决这个问题吗?
完全可以在 Azure AD 中拥有应用程序特定的自定义角色(称为
Azure AD App Roles
)。您需要在 Azure AD 应用程序中定义这些角色,然后为用户分配一个或多个这些应用程序角色。
当您获取应用程序的访问令牌时,这些角色将包含在令牌中(在
roles
或 role
声明中)。
请参阅此链接了解更多详细信息:https://learn.microsoft.com/en-us/entra/identity-platform/howto-add-app-roles-in-apps。