HasClaim() public method

Determines if a claim is contained within all the ClaimsIdentities in this ClaimPrincipal.
Each ClaimsIdentity is called. ClaimsIdentity.HasClaim.
if 'match' is null.
public HasClaim ( Predicate match ) : bool
match Predicate The predicate that performs the matching logic.
return bool
Exemplo n.º 1
0
 public static bool HasClaimCanEditProducts(ClaimsPrincipal user)
 {
     if (user.HasClaim("CanEditProducts", "true"))
     {
         return true;
     };
     return false;
 }
 public void HasClaim_DoesHaveClaim_ReturnsTrue()
 {
     var ci = new ClaimsIdentity(new Claim[]
     {
         new Claim("type1", "value1"),
         new Claim("type2", "value2"),
     });
     var cp = new ClaimsPrincipal(ci);
     Assert.IsTrue(cp.HasClaim("type1"));
 }
Exemplo n.º 3
0
 public static IHtmlContent PartialWithClaim(this IHtmlHelper helper, string partialName, object model, ClaimsPrincipal user, ClaimTypeEnum claimType, ClaimValueEnum claimValue)
 {
     if (user.HasClaim(claimType.ToString(), claimValue.ToString()))
     {
         return helper.Partial(partialName, model: model);
     }
     else
     {
         return helper.Raw(string.Empty);
     }
 }
        public void CanSerializeAndDeserializeAClaimsPrincipal()
        {
            var claims = new Claim[]{
                new Claim(Constants.ClaimTypes.Subject, "alice"),
                new Claim(Constants.ClaimTypes.Scope, "read"),
                new Claim(Constants.ClaimTypes.Scope, "write"),
            };
            var ci = new ClaimsIdentity(claims, Constants.AuthenticationMethods.Password);
            var cp = new ClaimsPrincipal(ci);

            var settings = new JsonSerializerSettings();
            settings.Converters.Add(new ClaimsPrincipalConverter());
            var json = JsonConvert.SerializeObject(cp, settings);

            cp = JsonConvert.DeserializeObject<ClaimsPrincipal>(json, settings);
            Assert.Equal(Constants.AuthenticationMethods.Password, cp.Identity.AuthenticationType);
            Assert.Equal(3, cp.Claims.Count());
            Assert.True(cp.HasClaim(Constants.ClaimTypes.Subject, "alice"));
            Assert.True(cp.HasClaim(Constants.ClaimTypes.Scope, "read"));
            Assert.True(cp.HasClaim(Constants.ClaimTypes.Scope, "write"));
        }
Exemplo n.º 5
0
        /// <summary>
        /// Determines whether the principal contains the specified claims.
        /// </summary>
        /// <param name="principal">The principal.</param>
        /// <param name="claims">The claims.</param>
        /// <returns><c>true</c> if the principal contains the specified claims; otherwise, <c>false</c>.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="claims"/> is <see langword="null"/>.</exception>
        /// <exception cref="ArgumentException">
        /// One of the items in the <paramref name="claims"/> collection is <see langword="null"/>.
        /// </exception>
        public static bool HasClaims(this ClaimsPrincipal principal, IEnumerable <Claim> claims)
        {
            claims.AssertNotNull(true, "claims");

            foreach (var claim in claims)
            {
                if (!principal.HasClaim(claim.Type, claim.Value))
                {
                    return(false);
                }
            }

            return(true);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Determines whether the principal contains the specified claim types.
        /// </summary>
        /// <param name="principal">The principal.</param>
        /// <param name="claimTypes">The claim types.</param>
        /// <returns>
        /// <c>true</c> if the principal contains the specified claim types; otherwise, <c>false</c>.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="claimTypes"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// One of the items in the <paramref name="claimTypes"/> collection is <see langword="null"/>.
        /// </exception>
        public static bool HasClaimTypes(this ClaimsPrincipal principal, IEnumerable <string> claimTypes)
        {
            claimTypes.AssertNotNull(true, "claimTypes");

            foreach (var type in claimTypes)
            {
                if (!principal.HasClaim(c => c.Type == type))
                {
                    return(false);
                }
            }

            return(true);
        }
Exemplo n.º 7
0
 private bool NotAuthorizedClaim(ClaimsPrincipal user)
 {
     return user.IsNotNull() && 
         Claim.IsNotNull() && 
         !user.HasClaim(Claim.Type, Claim.Value);
 }
Exemplo n.º 8
0
        // Constructor, pass in the security principal
        public UserAccount(ClaimsPrincipal user)
        {
            if (HttpContext.Current.Request.IsAuthenticated)
            {
                Principal = user;

                // Extract the role claims
                RoleClaims = user.Claims.Where(c => c.Type == ClaimTypes.Role).Select(c => c.Value);

                // User name
                Name = user.Identity.Name;

                // Extract the given name(s); if null or empty, then set an initial value
                string gn = user.Claims.SingleOrDefault(c => c.Type == ClaimTypes.GivenName).Value;
                if (string.IsNullOrEmpty(gn)) { gn = "(empty given name)"; }
                GivenName = gn;

                // Extract the surname; if null or empty, then set an initial value
                string sn = user.Claims.SingleOrDefault(c => c.Type == ClaimTypes.Surname).Value;
                if (string.IsNullOrEmpty(sn)) { sn = "(empty surname)"; }
                Surname = sn;

                IsAuthenticated = true;
                IsAdmin = user.HasClaim(ClaimTypes.Role, "Admin") ? true : false;
            }
            else
            {
                RoleClaims = new List<string>();
                Name = "anonymous";
                GivenName = "Unauthenticated";
                Surname = "Anonymous";
                IsAuthenticated = false;
                IsAdmin = false;
            }

            NamesFirstLast = $"{GivenName} {Surname}";
            NamesLastFirst = $"{Surname}, {GivenName}";
        }
Exemplo n.º 9
0
        /// <summary>
        ///     Produces the output identity that gets transformed into a token
        /// </summary>
        /// <param name="principal">The principal.</param>
        /// <param name="request">The request.</param>
        /// <param name="scope">The scope.</param>
        /// <returns>An IClaimsIdentity describing the subject</returns>
        protected override ClaimsIdentity GetOutputClaimsIdentity(ClaimsPrincipal principal,
            RequestSecurityToken request, Scope scope)
        {
            var requestDetails = (scope as RequestDetailsScope).RequestDetails;

            // externally authenticated user
            if (
                principal.HasClaim(
                    c => c.Type == Constants.Claims.IdentityProvider && c.Issuer == Constants.InternalIssuer))
            {
                Tracing.Information("Issuing a token for an external user.");
                return GetExternalOutputClaims(principal, requestDetails);
            }

            var userClaims = GetOutputClaims(principal, requestDetails, ClaimsRepository);
            var outputIdentity = new ClaimsIdentity(userClaims, "IdSrv");

            if (requestDetails.IsActAsRequest)
            {
                Tracing.Information("Issuing act as token");
                return GetActAsClaimsIdentity(outputIdentity, requestDetails);
            }
            Tracing.Information("Issuing identity token");
            return outputIdentity;
        }
Exemplo n.º 10
0
 public static bool IsPlayer(this ClaimsPrincipal principal) =>
 principal.HasClaim(AuthConstants.IsPlayer, AuthConstants.TrueValue);
Exemplo n.º 11
0
        public static HashSet <string> get_current_jurisdiction_id_set_for(System.Security.Claims.ClaimsPrincipal p_claims_principal)
        {
            HashSet <string> result = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            if (!p_claims_principal.HasClaim(c => c.Type == ClaimTypes.Name &&
                                             c.Issuer == "https://contoso.com"))
            {
                return(result);
            }

            if (p_claims_principal.HasClaim(c => c.Type == ClaimTypes.Role &&
                                            c.Value == "installation_admin"))
            {
                result.Add("/");
            }

            var user_name = p_claims_principal.Claims.Where(c => c.Type == ClaimTypes.Name).FirstOrDefault().Value;

            string jurisdicion_view_url      = $"{Program.config_couchdb_url}/jurisdiction/_design/sortable/_view/by_user_id?{user_name}";
            var    jurisdicion_curl          = new cURL("GET", null, jurisdicion_view_url, null, Program.config_timer_user_name, Program.config_timer_password);
            string jurisdicion_result_string = null;

            try
            {
                jurisdicion_result_string = jurisdicion_curl.execute();
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex);
                return(result);
            }

            var jurisdiction_view_response = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.common.model.couchdb.get_sortable_view_reponse_header <mmria.common.model.couchdb.user_role_jurisdiction> >(jurisdicion_result_string);

            var now = DateTime.Now;

            foreach (mmria.common.model.couchdb.get_sortable_view_response_item <mmria.common.model.couchdb.user_role_jurisdiction> jvi in jurisdiction_view_response.rows)
            {
                if (jvi.key != null && jvi.key == user_name)
                {
                    if (jvi.value.is_active != null && jvi.value.is_active.HasValue && jvi.value.is_active.Value)
                    {
                        bool add_item = true;

                        if (jvi.value.effective_start_date != null && jvi.value.effective_start_date.HasValue)
                        {
                            if (jvi.value.effective_start_date > now)
                            {
                                add_item = false;
                            }
                        }

                        if (jvi.value.effective_end_date != null && jvi.value.effective_end_date.HasValue)
                        {
                            if (jvi.value.effective_end_date.Value < now)
                            {
                                add_item = false;
                            }
                        }

                        if (add_item)
                        {
                            result.Add(jvi.value.jurisdiction_id);
                        }
                    }
                }
            }

            return(result);
        }
        protected virtual void SetPrincipal(HttpRequestMessage request, ClaimsPrincipal principal)
        {
            if (principal.Identity.IsAuthenticated)
            {
                string name = "unknown";

                if (!string.IsNullOrWhiteSpace(principal.Identity.Name))
                {
                    name = principal.Identity.Name;
                }
                else if (principal.HasClaim(c => c.Type == ClaimTypes.NameIdentifier ) && !string.IsNullOrWhiteSpace(principal.FindFirst(ClaimTypes.NameIdentifier).Value))
                {
                    name = principal.Identity.Name;
                }
                else if (principal.HasClaim(c => c.Type == "sub" ) && !string.IsNullOrWhiteSpace(principal.FindFirst("sub").Value))
                {
                    name = principal.Identity.Name;
                }
                else if (principal.Claims.First() != null)
                {
                    name = principal.Claims.First().Value;
                }

                Tracing.Verbose("Principal set for: " + name);
            }
            else
            {
                Tracing.Verbose("Setting anonymous principal.");
            }

            request.GetRequestContext().Principal = principal;

            if (_authN.Configuration.SetPrincipalOnRequestInstance)
            {
                request.Properties[PrincipalKey] = principal;
            }
        }
Exemplo n.º 13
0
        public static HashSet <(string jurisdiction_id, ResourceRightEnum ResourceRight)> get_current_jurisdiction_id_set_for(System.Security.Claims.ClaimsPrincipal p_claims_principal)
        {
            var result = new HashSet <(string jurisdiction_id, ResourceRightEnum ResourceRight)>();

            if (!p_claims_principal.HasClaim(c => c.Type == ClaimTypes.Name &&
                                             c.Issuer == "https://contoso.com"))
            {
                return(result);
            }

            if (p_claims_principal.HasClaim(c => c.Type == ClaimTypes.Role &&
                                            c.Value == "installation_admin"))
            {
                result.Add(("/", ResourceRightEnum.ReadUser));
                result.Add(("/", ResourceRightEnum.WriteUser));
                result.Add(("/", ResourceRightEnum.ReadJurisdiction));
                result.Add(("/", ResourceRightEnum.WriteJurisdiction));
            }

            var user_name = p_claims_principal.Claims.Where(c => c.Type == ClaimTypes.Name).FirstOrDefault().Value;

            string jurisdicion_view_url      = $"{Program.config_couchdb_url}/jurisdiction/_design/sortable/_view/by_user_id";
            var    jurisdicion_curl          = new cURL("GET", null, jurisdicion_view_url, null, Program.config_timer_user_name, Program.config_timer_password);
            string jurisdicion_result_string = null;

            try
            {
                jurisdicion_result_string = jurisdicion_curl.execute();
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex);
                return(result);
            }

            var jurisdiction_view_response = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.common.model.couchdb.get_sortable_view_reponse_header <mmria.common.model.couchdb.user_role_jurisdiction> >(jurisdicion_result_string);

            foreach (mmria.common.model.couchdb.get_sortable_view_response_item <mmria.common.model.couchdb.user_role_jurisdiction> jvi in jurisdiction_view_response.rows)
            {
                if (jvi.key != null && jvi.value.user_id == user_name)
                {
                    if
                    (
                        jvi.value.is_active == null ||
                        jvi.value.effective_start_date == null
                    )
                    {
                        continue;
                    }

                    if
                    (
                        !
                        (jvi.value.is_active.HasValue ||
                         jvi.value.effective_start_date.HasValue)
                    )
                    {
                        continue;
                    }



                    var now_date = DateTime.Now;

                    if
                    (
                        jvi.value.effective_end_date == null ||
                        jvi.value.effective_end_date.HasValue == false
                    )
                    {
                        jvi.value.effective_end_date = now_date;
                    }

                    if
                    (
                        !jvi.value.is_active.Value ||
                        !(jvi.value.effective_start_date.Value <= now_date) ||
                        !(now_date <= jvi.value.effective_end_date.Value)
                    )
                    {
                        continue;
                    }

                    switch (jvi.value.role_name)
                    {
                    case "abstractor":
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.ReadCase));
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.WriteCase));
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.ReadMetadata));
                        break;

                    case "committee_member":
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.ReadDeidentifiedCase));
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.ReadMetadata));
                        break;

                    case "form_designer":
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.WriteMetadata));
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.ReadMetadata));
                        break;

                    case "jurisdiction_admin":
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.ReadUser));
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.WriteUser));
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.ReadMetadata));
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.ReadJurisdiction));
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.WriteJurisdiction));
                        break;

                    case "installation_admin":
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.ReadUser));
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.WriteUser));
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.ReadMetadata));
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.ReadJurisdiction));
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.WriteJurisdiction));
                        break;
                    }
                }
            }

            return(result);
        }
 private bool OrderBelongsToPhotographer(System.Security.Claims.ClaimsPrincipal currentUser, string photographer)
 {
     return(currentUser.HasClaim(c => c.Type == ClaimTypes.Email && c.Value == photographer));
 }
Exemplo n.º 15
0
 public static bool IsAuthorised(this ClaimsPrincipal principal) =>
 principal.HasClaim(AuthConstants.IsAuthorised, AuthConstants.TrueValue);
Exemplo n.º 16
0
 public static bool IsAttendee(this ClaimsPrincipal principal) =>
 principal.HasClaim(AuthConstants.IsAttendee, AuthConstants.TrueValue);
 public static bool IsAdmin(this ClaimsPrincipal user)
 {
     return(user?.HasClaim(BlogConstants.Claims.Admin, BlogConstants.Claims.Admin) == true);
 }