From abb3e9b848b44ee9f0e67538eba2c8f0054e6603 Mon Sep 17 00:00:00 2001 From: Chris Winland Date: Mon, 29 Jul 2024 14:15:13 -0400 Subject: [PATCH] Add IdentityHelper extensions --- .../Extensions/IdentityHelperExtensions.cs | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 FastMoq.Core/Extensions/IdentityHelperExtensions.cs diff --git a/FastMoq.Core/Extensions/IdentityHelperExtensions.cs b/FastMoq.Core/Extensions/IdentityHelperExtensions.cs new file mode 100644 index 0000000..4821d9c --- /dev/null +++ b/FastMoq.Core/Extensions/IdentityHelperExtensions.cs @@ -0,0 +1,80 @@ +using Microsoft.AspNetCore.Http; +using System.Reflection; +using System.Security.Claims; + +namespace FastMoq.Extensions +{ + /// + /// Class IdentityHelper. + /// + public static class IdentityHelperExtensions + { + /// + /// Sets the user. + /// + /// The context. + /// The principal. + public static void SetUser(this HttpContext context, ClaimsPrincipal principal) + { + context.User = principal; + } + + /// + /// Sets the user. + /// + /// The context. + /// The principal. + public static void SetUser(this HttpContext context, ClaimsIdentity identity) + { + context.User = new ClaimsPrincipal(identity); + } + + /// + /// Creates a claim. + /// + /// The type of claim. Must be from . + /// Value of the claim. + /// Claim Properties. + /// Indicates if type is validated. If custom type is allowed, then the type string is not validated. + public static Claim CreateClaim(string type, string value, Dictionary? properties = null, bool allowCustomType = false) + { + if (!allowCustomType && !IsValidClaimType(type)) + { + throw new ArgumentException("Invalid claim type", nameof(type)); + } + + var claim = new Claim(type, value); + + foreach (var property in properties ?? new()) + { + claim.Properties.Add(property.Key, property.Value); + } + + return claim; + } + + /// + /// Creates the principal. + /// + /// The claims. + /// Type of the authentication. + /// ClaimsPrincipal. + public static ClaimsPrincipal CreatePrincipal(IEnumerable claims, string? authenticationType = null) => + new(new ClaimsIdentity(claims, authenticationType)); + + /// + /// Determines whether given type is included as a constant. Custom types may be valid, but this method will return false. + /// + /// The type. + /// true if type in ; otherwise, false. + public static bool IsValidClaimType(string type) + { + var claimTypes = typeof(ClaimTypes).GetFields(BindingFlags.Public | BindingFlags.Static) + .Where(f => f.FieldType == typeof(string)) + .Select(f => (string?) f.GetValue(null)) + .Where(f => f is not null); + + return claimTypes.Contains(type); + } + } +} \ No newline at end of file