From 163868b2a40832ca832cf10c1e72f449fc0d6f0b Mon Sep 17 00:00:00 2001 From: Stuart Ferguson Date: Mon, 30 May 2022 15:45:41 +0100 Subject: [PATCH] Added Claims Helper --- Shared/General/ClaimsHelper.cs | 97 ++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 Shared/General/ClaimsHelper.cs diff --git a/Shared/General/ClaimsHelper.cs b/Shared/General/ClaimsHelper.cs new file mode 100644 index 00000000..07bc2f9a --- /dev/null +++ b/Shared/General/ClaimsHelper.cs @@ -0,0 +1,97 @@ +namespace Shared.General +{ + using System; + using System.Diagnostics.CodeAnalysis; + using System.Linq; + using System.Security.Claims; + using Exceptions; + + [ExcludeFromCodeCoverage] + public class ClaimsHelper + { + #region Methods + + /// + /// Gets the user claims. + /// + /// The user. + /// Type of the custom claim. + /// The default value. + /// + /// No claim [{customClaimType}] found for user id [{userIdClaim.Value} + public static Claim GetUserClaim(ClaimsPrincipal user, + String customClaimType, + String defaultValue = "") { + Claim userClaim = null; + + if (ClaimsHelper.IsPasswordToken(user)) { + // Get the claim from the token + userClaim = user.Claims.SingleOrDefault(c => c.Type.ToLower() == customClaimType.ToLower()); + + if (userClaim == null) { + throw new NotFoundException($"Claim type [{customClaimType}] not found"); + } + } + else { + userClaim = new Claim(customClaimType, defaultValue); + } + + return userClaim; + } + + /// + /// Determines whether [is client token] [the specified user]. + /// + /// The user. + /// + /// true if [is client token] [the specified user]; otherwise, false. + /// + public static Boolean IsPasswordToken(ClaimsPrincipal user) { + Boolean result = false; + + Claim userIdClaim = user.Claims.SingleOrDefault(c => c.Type == ClaimTypes.NameIdentifier); + + if (userIdClaim != null) { + result = true; + } + + return result; + } + + /// + /// Determines whether [is user roles valid] [the specified user]. + /// + /// The user. + /// The allowed roles. + /// + /// true if [is user roles valid] [the specified user]; otherwise, false. + /// + public static Boolean IsUserRolesValid(ClaimsPrincipal user, + String[] allowedRoles) { + if (ClaimsHelper.IsPasswordToken(user) == false) { + return true; + } + + return allowedRoles.Any(r => user.IsInRole(r)); + } + + /// + /// Validates the route parameter. + /// + /// + /// The route parameter. + /// The user claim. + public static Boolean ValidateRouteParameter(T routeParameter, + Claim userClaim) { + if (userClaim != null && userClaim.Value != String.Empty) { + if (routeParameter.ToString() != userClaim.Value) { + return false; + } + } + + return true; + } + + #endregion + } +} \ No newline at end of file