Skip to content

Commit

Permalink
VCST-2048: Extend ClaimsPrincipalExtensions with GetUserId and GetUse…
Browse files Browse the repository at this point in the history
…rName (#2855)

feat: Extend ClaimsPrincipalExtensions with GetCurrentUserId and resolving of UserIdClaimTypes based on IdentityOptions settings.
  • Loading branch information
OlegoO authored Nov 1, 2024
1 parent d917abf commit fa4e48b
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,37 @@ namespace VirtoCommerce.Platform.Core.Security
{
public static class ClaimsPrincipalExtensions
{
public static string[] UserIdClaimTypes { get; set; } = [];

public static string[] UserNameClaimTypes { get; set; } = [];

public static string GetUserId(this ClaimsPrincipal claimsPrincipal)
{
return GetClaimValue(claimsPrincipal, UserIdClaimTypes);
}

public static string GetUserName(this ClaimsPrincipal claimsPrincipal)
{
return GetClaimValue(claimsPrincipal, UserNameClaimTypes);
}

private static string GetClaimValue(ClaimsPrincipal claimsPrincipal, string[] claimTypes)
{
if (claimsPrincipal != null)
{
foreach (var claimType in claimTypes)
{
var value = claimsPrincipal.FindFirstValue(claimType);
if (!string.IsNullOrEmpty(value))
{
return value;
}
}
}

return null;
}

public static Permission FindPermission(this ClaimsPrincipal principal, string permissionName, JsonSerializerSettings jsonSettings)
{
return FindPermissions(principal, permissionName, jsonSettings).FirstOrDefault();
Expand All @@ -27,7 +58,6 @@ public static IList<Permission> FindPermissions(this ClaimsPrincipal principal,
return result;
}


public static bool HasGlobalPermission(this ClaimsPrincipal principal, string permissionName)
{
// TODO: Check cases with locked user
Expand Down
4 changes: 4 additions & 0 deletions src/VirtoCommerce.Platform.Web/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
Expand Down Expand Up @@ -274,6 +275,9 @@ public void ConfigureServices(IServiceCollection services)
options.ClaimsIdentity.UserNameClaimType = OpenIddictConstants.Claims.Subject;
options.ClaimsIdentity.UserIdClaimType = OpenIddictConstants.Claims.Name;
options.ClaimsIdentity.RoleClaimType = OpenIddictConstants.Claims.Role;

ClaimsPrincipalExtensions.UserIdClaimTypes = [options.ClaimsIdentity.UserIdClaimType, ClaimTypes.NameIdentifier];
ClaimsPrincipalExtensions.UserNameClaimTypes = [options.ClaimsIdentity.UserNameClaimType];
});

services.ConfigureOptions<ConfigureSecurityStampValidatorOptions>();
Expand Down

0 comments on commit fa4e48b

Please sign in to comment.