-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
RoleClaimsProvider.cs
66 lines (53 loc) · 1.88 KB
/
RoleClaimsProvider.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
using System.Security.Claims;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
using OrchardCore.Security;
using OrchardCore.Users;
using OrchardCore.Users.Services;
namespace OrchardCore.Roles;
public class RoleClaimsProvider : IUserClaimsProvider
{
private readonly UserManager<IUser> _userManager;
private readonly RoleManager<IRole> _roleManager;
private readonly ISystemRoleNameProvider _systemRoleNameProvider;
private readonly IdentityOptions _identityOptions;
public RoleClaimsProvider(
UserManager<IUser> userManager,
RoleManager<IRole> roleManager,
ISystemRoleNameProvider systemRoleNameProvider,
IOptions<IdentityOptions> identityOptions)
{
_userManager = userManager;
_roleManager = roleManager;
_systemRoleNameProvider = systemRoleNameProvider;
_identityOptions = identityOptions.Value;
}
public async Task GenerateAsync(IUser user, ClaimsIdentity claims)
{
if (!_userManager.SupportsUserRole)
{
return;
}
var isAdministrator = false;
if (await _userManager.IsInRoleAsync(user, await _systemRoleNameProvider.GetAdminRoleAsync()))
{
claims.AddClaim(StandardClaims.SiteOwner);
isAdministrator = true;
}
var roleNames = await _userManager.GetRolesAsync(user);
foreach (var roleName in roleNames)
{
claims.AddClaim(new Claim(_identityOptions.ClaimsIdentity.RoleClaimType, roleName));
if (isAdministrator || !_roleManager.SupportsRoleClaims)
{
continue;
}
var role = await _roleManager.FindByNameAsync(roleName);
if (role == null)
{
continue;
}
claims.AddClaims(await _roleManager.GetClaimsAsync(role));
}
}
}