-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMsGraphClaimsTransformation.cs
More file actions
68 lines (61 loc) · 2.9 KB
/
MsGraphClaimsTransformation.cs
File metadata and controls
68 lines (61 loc) · 2.9 KB
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
// <copyright file="MsGraphClaimsTransformation.cs" company="Moonrise Software, LLC">
// Copyright (c) Moonrise Software, LLC. All rights reserved.
// Licensed under the GNU Public License, Version 3.0 (https://www.gnu.org/licenses/gpl-3.0.html)
// See https://github.com/MoonriseSoftwareCalifornia/CosmosCMS
// for more information concerning the license and the contributors participating to this project.
// </copyright>
namespace Cosmos.MicrosoftGraph
{
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
/// <summary>
/// This class is used to transform the claims principal and add the group claims.
/// </summary>
// SEE: https://damienbod.com/2021/09/06/using-azure-security-groups-in-asp-net-core-with-an-azure-b2c-identity-provider/
public class MsGraphClaimsTransformation
{
private readonly MsGraphService msGraphService;
/// <summary>
/// Initializes a new instance of the <see cref="MsGraphClaimsTransformation"/> class.
/// </summary>
/// <param name="msGraphService">Microsoft Graph Service.</param>
public MsGraphClaimsTransformation(MsGraphService msGraphService)
{
this.msGraphService = msGraphService;
}
/// <summary>
/// Returns a claims principal with the group claims added.
/// </summary>
/// <param name="principal">The claims principal.</param>
/// <returns>A <see cref="Task{TResult}"/> representing the result of the asynchronous operation.</returns>
public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
ClaimsIdentity claimsIdentity = new ();
var groupClaimType = "group";
if (!principal.HasClaim(claim => claim.Type == groupClaimType))
{
var objectidentifierClaimType = "http://schemas.microsoft.com/identity/claims/objectidentifier";
var objectIdentifier = principal.Claims.FirstOrDefault(t => t.Type == objectidentifierClaimType);
if (objectIdentifier != null)
{
var groups = await this.msGraphService.GetGraphApiUserMemberGroups(objectIdentifier.Value);
if (groups != null)
{
foreach (var group in groups)
{
if (!string.IsNullOrEmpty(group.DisplayName) && !string.IsNullOrEmpty(group.Id))
{
var claim = new Claim(groupClaimType, group.DisplayName);
claim.Properties.Add("id", group.Id);
claimsIdentity.AddClaim(claim);
}
}
}
}
}
principal.AddIdentity(claimsIdentity);
return principal;
}
}
}