HasClaim() public method

Determines if a claim is contained within this ClaimsIdentity.
if 'match' is null.
public HasClaim ( Predicate match ) : bool
match Predicate The function that performs the matching logic.
return bool
コード例 #1
0
 public static IEnumerable<Claim> CreateRolesForClaims(ClaimsIdentity user) {
     List<Claim> claims = new List<Claim>();
     if (user.HasClaim(x => x.Type == ClaimTypes.StateOrProvince && x.Issuer == "RemoteClaims" && x.Value == "DC")
         && user.HasClaim(x => x.Type == ClaimTypes.Role && x.Value == "Employees")) {
         claims.Add(new Claim(ClaimTypes.Role, "DCStaff"));
     }
     return claims;            
 }
コード例 #2
0
        public static IEnumerable<Claim> CreateRolesBasedOnClaims(ClaimsIdentity identity)
        {
            List<Claim> claims = new List<Claim>();

            if(identity.HasClaim(c => c.Type == "FTE" && c.Value == "1") && identity.HasClaim(ClaimTypes.Role, "Admin"))
            {
                claims.Add(new Claim(ClaimTypes.Role, "IncidentResolvers"));
            }

            return claims;
        }
        public async static Task<IEnumerable<Claim>> GetClaims(ClaimsIdentity user)
        {
            List<Claim> claims = new List<Claim>();
            //Only client account will be processed for this type of claim
            if (user != null && user.IsAuthenticated && user.HasClaim(c => c.Type == ClaimTypes.Role && c.Value == AuthorizationRoles.Role_Client))
            {
                using (edisDbEntities db = new edisDbEntities())
                {

                    var userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(new ApplicationDbContext()));
                    var userProfile = await userManager.FindByNameAsync(user.Name);
                    if (userProfile != null)
                    {
                        var profile = db.RiskProfiles.FirstOrDefault(c => c.Client.ClientUserID == userProfile.Id);
                        if (profile != null)
                        {
                            claims.Add(CreateClaim(ClaimType_clientRiskProfileCompletion, ClaimValue_clientRiskProfile_Completed));
                        }
                        else
                        {
                            claims.Add(CreateClaim(ClaimType_clientRiskProfileCompletion, ClaimValue_clientRiskProfile_Incomplete));
                        }
                    }
                }
            }

            return claims;
        }
コード例 #4
0
        public Task<ClaimsIdentity> CreateIdentityAsync(User user, string authenticationType, ClaimsIdentity externalIdentity)
        {
            var identity = new ClaimsIdentity(authenticationType, ClaimTypes.Name, ClaimTypes.Role);

            identity.AddClaims(externalIdentity.Claims);
            identity.AddClaim(new Claim(ClaimTypes.Name, user.Name, ClaimValueTypes.String));
            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString(), ClaimValueTypes.String));

            if (user.IsAdmin)
            {
                identity.AddClaim(new Claim(ClaimTypes.Role, "admin", ClaimValueTypes.String));
            }

            if (externalIdentity.HasClaim(claim => claim.Type == "urn:reddit:moderator_of"))
            {
                identity.AddClaim(new Claim(ClaimTypes.Role, "moderator", ClaimValueTypes.String));
            }

            if (user.IsBanned)
            {
                identity.AddClaim(new Claim(ClaimTypes.Role, "banned", ClaimValueTypes.String));
            }

            return Task.FromResult(identity);
        }
コード例 #5
0
        public async static Task<IEnumerable<Claim>> GetClaims(ClaimsIdentity user)
        {
            List<Claim> claims = new List<Claim>();
            using (edisDbEntities db = new edisDbEntities())
            {
                if (user.HasClaim(c => c.Type == ClaimTypes.Role && c.Value == AuthorizationRoles.Role_Client))
                {

                    var userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(new ApplicationDbContext()));
                    var userProfile = await userManager.FindByNameAsync(user.Name);

                    var client = db.Clients.FirstOrDefault(c => c.ClientUserID == userProfile.Id);
                    if (client != null)
                    {
                        var clientGroup = db.ClientGroups.FirstOrDefault(c => c.ClientGroupID == client.ClientGroupID);
                        if (clientGroup != null && clientGroup.MainClientID == client.ClientUserID)
                        {
                            claims.Add(CreateClaim(ClaimType_ClientGroupLeader, ClaimValue_ClientGroupLeader_Leader));
                        }
                        else
                        {
                            claims.Add(CreateClaim(ClaimType_ClientGroupLeader, ClaimValue_ClientGroupLeader_Member));
                        }
                    }
                }
            }
            return claims;
        }
コード例 #6
0
 private List<string> GetModules(ClaimsIdentity ci)
 {
     if (ci.HasClaim(c => c.Type == IlluminateClaimTypes.OrgModules))
     {
         var concatModules = ci.FindFirst(c => c.Type == IlluminateClaimTypes.OrgModules).Value;
         return  Organisation.DecatenateModules(concatModules);
     }
     return new List<string> { "sickness", "leave" };
 }
コード例 #7
0
 private bool CheckIdentityAndBasicClaims(ClaimsIdentity ci)
 {
     if (ci == null)
         return false;
     if (!ci.HasClaim(c => c.Type == ClaimTypes.NameIdentifier))
     {
         GetLogger().Info("NameIdentifier claim not present");
         return false;
     }
     return true;
 }
コード例 #8
0
ファイル: ApplicationUser.cs プロジェクト: Tmaturano/PetSuite
 private async Task SetExternalProperties(ClaimsIdentity identity, ClaimsIdentity ext)
 {
     if (ext != null)
     {
         var ignoreClaim = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims";
         // Adicionando Claims Externos no Identity
         foreach (var c in ext.Claims)
         {
             if (!c.Type.StartsWith(ignoreClaim))
                 if (!identity.HasClaim(c.Type, c.Value))
                     identity.AddClaim(c);
         }
     }
 }
コード例 #9
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            var user = await UserManager.FindAsync(context.UserName, context.Password);
            var data = await context.Request.ReadFormAsync();

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("userId", user.Id.ToString()));

            foreach (var role in UserManager.GetRoles(user.Id))
            {
                identity.AddClaim(new Claim(ClaimTypes.Role, role.ToString()));
            }

            foreach (var claim in UserManager.GetClaims(user.Id))
            {
                identity.AddClaim(new Claim(claim.Type, claim.Value));
            }

            var isSuperAdmin = identity.HasClaim(ClaimTypes.Role, RoleClassification.SuperAdministrator.ToString());
            Guid cloakCompanyId;
            Guid companyId;

            if (data["cloakCompanyId"] != null && Guid.TryParse(data["cloakCompanyId"], out cloakCompanyId) && isSuperAdmin)
            {
                // Super administrator cloaking of a company.
                companyId = cloakCompanyId;
            }
            else
            {
                // Typical user sign in.
                companyId = user.CompanyId;
            }

            identity.AddClaim(new Claim("companyId", companyId.ToString()));
            identity.AddClaim(new Claim("isSuper", isSuperAdmin.ToString()));

            var properties = CreateProperties(user.Id, companyId, isSuperAdmin);
            var ticket = new AuthenticationTicket(identity, properties);

            context.Validated(ticket);
        }
コード例 #10
0
        protected virtual bool AuthorizeAdministration(Collection<Claim> resource, ClaimsIdentity id)
        {
            var roleResult = id.HasClaim(ClaimTypes.Role, Constants.Roles.IdentityServerAdministrators);
            if (!roleResult)
            {
                if (resource[0].Value != Constants.Resources.UI)
                {
                    Tracing.Error(
                        string.Format("Administration authorization failed because user {0} is not in the {1} role",
                            id.Name, Constants.Roles.IdentityServerAdministrators));
                }
            }

            return roleResult;
        }
コード例 #11
0
        protected virtual bool AuthorizeTokenIssuance(Collection<Claim> resource, ClaimsIdentity id)
        {
            if (!id.IsAuthenticated)
            {
                logger.Error("Authorization for token issuance failed because the user is anonymous");                
                return false;
            }

            if (ConfigurationRepository.Global.EnforceUsersGroupMembership)
            {
                var roleResult = id.HasClaim(ClaimTypes.Role, Constants.Roles.IdentityServerUsers);
                if (!roleResult)
                {
                     logger.Error(string.Format("Authorization for token issuance failed because user {0} is not in the {1} role", id.Name, Constants.Roles.IdentityServerUsers));
                }
                return roleResult;
            }
            return true;
        }
コード例 #12
0
        public static IEnumerable<Claim> AddAdministratorAccessToRoles(Controller ctrl,  ClaimsIdentity user)
        {
            if (user.IsAuthenticated && user.HasClaim(x => (x.Type == ClaimTypes.Role) && (x.Value == "Administrators")))
            {
                var roleManager = ctrl.HttpContext.GetOwinContext().GetUserManager<AppRoleManager>();
                IEnumerable<AppRole> roles = roleManager.Roles.Where(x => x.IsAvailableForAdministrators);
                List<Claim> claims = new List<Claim>();

                foreach (AppRole role in roles)
                {
                    claims.Add(new Claim(ClaimTypes.Role, role.Name, "Authomaticly provided for Administrator"));
                }
                return claims;
            }
            else
            {
                return new List<Claim>();
            }
        }
コード例 #13
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            string user = context.UserName;
            string password = context.Password;

            Usuario dbUser = this.db.Usuario.Where(u => u.login == context.UserName).FirstOrDefault();

            if (password != "password")
            {
                context.SetError("invalid_grant", "Contrseña incorrecta.");
                return;
            }
            if (dbUser == null)
            {
                context.SetError("invalid_grant", "Usuario inexistente.");
                return;
            }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));


            foreach (RolxUsuario ur in dbUser.RolxUsuario )
            {
                foreach (FuncionXRol rp in ur.Rol.FuncionXRol)
                {   
                    if (!identity.HasClaim(ClaimTypes.Role, rp.Funcion.Descripcion))
                    {
                        identity.AddClaim(new Claim(ClaimTypes.Role, rp.Funcion.Descripcion));
                    }
                }
            }

            context.Validated(identity);

        }
コード例 #14
0
        /// <summary>
        /// This static method is setup as a delegate in Startup.Auth and will be called each time a userIdentity is created
        /// </summary>
        /// <param name="userIdentity">the ClaimsIdentity created from CRM</param>
        /// <param name="manager">the user manager used to add claims in the CRM storage</param>
        public static async Task AddCustomUserClaims(System.Security.Claims.ClaimsIdentity userIdentity, UserManager <CrmIdentityUser <string>, string> manager)
        {
            // Here you can add your custom claims to the userIdentity
            // Below is an example of how to add a custom claim:

            // Check if the customClaim has been retrieved from CRM storage
            if (!userIdentity.HasClaim("MyClaimType", "MyClaimValue"))
            {
                // Add the claim to the CRM Claim storage
                System.Security.Claims.Claim customClaim = new Claim("MyClaimType", "MyClaimValue");
                IdentityResult result = await manager.AddClaimAsync(userIdentity.GetUserId(), customClaim);

                // If all goes well, add the claim to the userIdentity. Next time the user logs in
                if (result.Succeeded)
                {
                    userIdentity.AddClaim(customClaim);
                }
                else
                {
                    // Handle the error
                }
            }
        }
コード例 #15
0
ファイル: SecurityService.cs プロジェクト: jechtom/DevUpdater
 public bool GetIdentityIsAuthenticated(ClaimsIdentity identity)
 {
     var result = identity.HasClaim(c => c.Type == IsKnownClaimType && c.Issuer == ClaimIssuer && c.Value.Equals("true", StringComparison.OrdinalIgnoreCase));
     return result;
 }
コード例 #16
0
        private async Task<ClaimsIdentity> StoreExternalClaims(ClaimsIdentity userIdentity) {
            ClaimsIdentity externalIdentity = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
            if (externalIdentity != null) {
                var currentClaims = await UserManager.GetClaimsAsync(userIdentity.GetUserId());
                foreach (var claim in externalIdentity.Claims) {
                    if (!claim.Type.StartsWith("http://schemas.xmlsoap.org/ws/2005/05/identity/claims")) {

                        if (userIdentity.HasClaim(c => c.Type == claim.Type && c.Issuer.Contains("LOCAL"))) {
                            var toRemoveClaim = userIdentity.Claims.FirstOrDefault(c => c.Type == claim.Type && c.Issuer.Contains("LOCAL"));
                            if (toRemoveClaim != null) {
                                userIdentity.RemoveClaim(toRemoveClaim);
                            }
                        }

                        if (!userIdentity.HasClaim(claim.Type, claim.Value)) {
                            // Add to claims
                            userIdentity.AddClaim(claim);

                            // Remove current claim
                            var currentClaim = currentClaims.FirstOrDefault(c => c.Type == claim.Type);
                            if (currentClaim != null)
                                await UserManager.RemoveClaimAsync(userIdentity.GetUserId(), currentClaim);

                            // Store claim to database
                            await UserManager.AddClaimAsync(userIdentity.GetUserId(), claim);
                        }
                    }
                }
            }

            return userIdentity;
        }
コード例 #17
0
        private async Task SetExternalProperties(ClaimsIdentity identity)
        {
            // get external claims captured in Startup.ConfigureAuth
            ClaimsIdentity ext = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);

            if (ext != null)
            {
                var ignoreClaim = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims";
                // add external claims to identity
                foreach (var c in ext.Claims)
                {
                    if (!c.Type.StartsWith(ignoreClaim))
                        if (!identity.HasClaim(c.Type, c.Value))
                            identity.AddClaim(c);
                }
            }
        }
コード例 #18
0
        private async Task<ClaimsIdentity> RemoveExternalClaims(ClaimsIdentity userIdentity, string loginProvider) {
            var currentClaims = await UserManager.GetClaimsAsync(userIdentity.GetUserId());
            foreach (var providerClaim in AuthenticationManager.User.Claims.Where(c => c.Type.StartsWith("urn:" + loginProvider.ToLower()))) {
                if (!providerClaim.Type.StartsWith("http://schemas.xmlsoap.org/ws/2005/05/identity/claims")) {
                    if (userIdentity.HasClaim(c => c.Type == providerClaim.Type)) {

                        if (userIdentity.HasClaim(c => c.Type == providerClaim.Type)) {
                            var toRemoveClaim = userIdentity.Claims.FirstOrDefault(c => c.Type == providerClaim.Type);
                            if (toRemoveClaim != null) {
                                userIdentity.RemoveClaim(toRemoveClaim);
                            }
                        }

                        // remove from database
                        var currentClaim = currentClaims.FirstOrDefault(c => c.Type == providerClaim.Type);
                        if (currentClaim != null)
                            await UserManager.RemoveClaimAsync(userIdentity.GetUserId(), currentClaim);
                    }
                }
            }
            return userIdentity;
        }
コード例 #19
0
ファイル: ClaimsIdentityTest.cs プロジェクト: nlhepler/mono
		public void HasClaim_typeValue_Works()
		{
			var id = new ClaimsIdentity(
			new[] {
				new Claim ("claim_type", "claim_value"),
				new Claim (ClaimsIdentity.DefaultNameClaimType, "claim_name_value"), 
				new Claim ("claim_role_type", "claim_role_value"), 
			}, "test_authority");

			Assert.IsTrue (id.HasClaim("claim_type", "claim_value"), "#1");
			Assert.IsTrue (id.HasClaim("cLaIm_TyPe", "claim_value"), "#2");
			Assert.IsFalse (id.HasClaim("claim_type", "cLaIm_VaLuE"), "#3");
			Assert.IsFalse (id.HasClaim("Xclaim_type", "claim_value"), "#4");
			Assert.IsFalse (id.HasClaim("claim_type", "Xclaim_value"), "#5");
	  }