Strapi V4配置Microsoft登录后如何修改用户存储数据
同步Azure AD用户组/角色到Strapi V4用户并实时更新
要实现将Azure AD的用户组、角色等字段同步到Strapi User模型,且每次登录自动更新,需按以下步骤操作:
1. 扩展Strapi User模型,添加自定义字段
先给Strapi默认的User模型添加存储组和角色的字段:
- 打开路径
src/api/user/content-types/user/schema.json(若文件不存在,可通过Strapi后台生成后编辑) - 在
attributes节点下新增所需字段,示例如下:
{ "attributes": { // 保留原有字段(如email、username等) "groups": { "type": "json", "default": [] }, "azureRoles": { "type": "json", "default": [] } } }
- 重启Strapi服务,使模型变更生效。
2. 自定义Azure AD提供商的用户同步逻辑
修改Strapi Auth插件配置,自定义从Azure AD获取用户信息、同步到Strapi User的逻辑,确保每次登录都更新字段:
- 打开或创建
config/plugins.js文件,添加以下配置(替换占位符为你的Azure AD租户ID等信息):
module.exports = ({ env }) => ({ auth: { config: { providers: { 'azure-ad': { provider: 'azure-ad', authUrl: 'https://login.microsoftonline.com/[你的租户ID]/oauth2/v2.0/authorize', tokenUrl: 'https://login.microsoftonline.com/[你的租户ID]/oauth2/v2.0/token', // 必须包含User.Read权限,同时需在Azure AD后台授予Graph API的组读取权限 scope: 'openid email profile User.Read GroupMember.Read.All', // 异步获取用户信息,包括调用Graph API拉取组和角色 profile: async (profile, tokens) => { // 调用Graph API获取用户所属组 const groupsRes = await fetch('https://graph.microsoft.com/v1.0/me/memberOf', { headers: { Authorization: `Bearer ${tokens.access_token}` } }); const groupsData = await groupsRes.json(); const groupNames = groupsData.value?.map(group => group.displayName) || []; // 调用Graph API获取用户的应用角色 const rolesRes = await fetch('https://graph.microsoft.com/v1.0/me/appRoleAssignments', { headers: { Authorization: `Bearer ${tokens.access_token}` } }); const rolesData = await rolesRes.json(); const roleDetails = rolesData.value?.map(role => ({ id: role.appRoleId, name: role.resourceDisplayName })) || []; return { id: profile.id, username: profile.displayName, email: profile.email || profile.upn, groups: groupNames, azureRoles: roleDetails }; }, // 自定义用户创建/更新逻辑,确保登录时同步最新数据 async createUser({ profile }) { // 检查用户是否已存在 const existingUser = await strapi.query('plugin::users-permissions.user').findOne({ where: { email: profile.email } }); if (existingUser) { // 存在则更新字段 return strapi.query('plugin::users-permissions.user').update({ where: { id: existingUser.id }, data: { username: profile.username, groups: profile.groups, azureRoles: profile.azureRoles } }); } // 不存在则创建新用户,生成随机密码(AD登录无需本地密码) return strapi.query('plugin::users-permissions.user').create({ data: { ...profile, password: strapi.service('plugin::users-permissions.user').generatePassword(), confirmed: true // 跳过邮箱验证 } }); } } } } } });
关键注意事项:
- Azure AD权限配置:需在Azure AD应用注册中,添加
GroupMember.Read.All(读取组)和User.Read(读取用户基本信息)的Delegated权限,并授予管理员同意,否则Graph API调用会失败。 - 字段映射:根据Azure AD实际返回的字段调整
profile函数中的数据提取逻辑,部分字段可能在profile._json下。 - 密码处理:Strapi User模型要求必须有密码字段,因此创建用户时需生成随机密码,AD登录用户不会用到该密码。
3. 验证效果
重启Strapi服务后,使用Azure AD账号登录,进入Strapi后台查看用户详情,即可看到groups和azureRoles字段已同步,且每次登录都会更新为Azure AD中的最新数据。
内容的提问来源于stack exchange,提问作者David Beaudway
相关产品推荐
相关产品推荐

