-
Notifications
You must be signed in to change notification settings - Fork 0
/
CustomAccountFactory.cs
86 lines (74 loc) · 2.81 KB
/
CustomAccountFactory.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
using Microsoft.AspNetCore.Components.WebAssembly.Authentication.Internal;
using Microsoft.Extensions.Logging;
public class CustomUserFactory
: AccountClaimsPrincipalFactory<CustomUserAccount>
{
private readonly ILogger<CustomUserFactory> logger;
private readonly IHttpClientFactory clientFactory;
public CustomUserFactory(IAccessTokenProviderAccessor accessor,
IHttpClientFactory clientFactory,
ILogger<CustomUserFactory> logger)
: base(accessor)
{
this.clientFactory = clientFactory;
this.logger = logger;
}
public async override ValueTask<ClaimsPrincipal> CreateUserAsync(
CustomUserAccount account,
RemoteAuthenticationUserOptions options)
{
var initialUser = await base.CreateUserAsync(account, options);
if (initialUser.Identity.IsAuthenticated)
{
var userIdentity = (ClaimsIdentity)initialUser.Identity;
foreach (var role in account.Roles)
{
userIdentity.AddClaim(new Claim("role", role));
}
if (userIdentity.HasClaim(c => c.Type == "hasgroups"))
{
try
{
var client = clientFactory.CreateClient("GraphAPI");
var response = await client.GetAsync("v1.0/me/memberOf");
if (response.IsSuccessStatusCode)
{
var userObjects = await response.Content
.ReadFromJsonAsync<DirectoryObjects>();
foreach (var obj in userObjects?.Values)
{
userIdentity.AddClaim(new Claim("group", obj.Id));
}
var claim = userIdentity.Claims.FirstOrDefault(
c => c.Type == "hasgroups");
userIdentity.RemoveClaim(claim);
}
else
{
logger.LogError("Graph API request failure: {REASON}",
response.ReasonPhrase);
}
}
catch (AccessTokenNotAvailableException exception)
{
logger.LogError("Graph API access token failure: {Message}",
exception.Message);
}
}
else
{
foreach (var group in account.Groups)
{
userIdentity.AddClaim(new Claim("group", group));
}
}
}
return initialUser;
}
}