RemoveClaim() public méthode

It is possible that a Claim returned from Claims cannot be removed. This would be the case for 'External' claims that are provided by reference.

object.ReferenceEquals is used to 'match'.

if 'claim' cannot be removed.
public RemoveClaim ( Claim claim ) : void
claim Claim the to match.
Résultat void
Exemple #1
0
        public static string CreateJwtToken(AuthenticationTicket data, string issuer, SigningCredentials signingCredentials)
        {
            string audience = issuer;

            // As JWT doesn't have a mechanism of passing metadata about what claim should be the name/subject the JWT handler
            // users the default Name claim type. If the identity has another claim type as the name type we need to 
            // switch it to the DefaultNameClaimType.
            var identity = new ClaimsIdentity(data.Identity);
            if (identity.NameClaimType != ClaimsIdentity.DefaultNameClaimType && !string.IsNullOrWhiteSpace(identity.Name))
            {
                identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, identity.Name));
                identity.RemoveClaim(identity.Claims.First(c => c.Type == identity.NameClaimType));
            }

            // And now do the same for roles.
            List<Claim> roleClaims = identity.Claims.Where(c => c.Type == identity.RoleClaimType).ToList();
            if (identity.RoleClaimType != ClaimsIdentity.DefaultRoleClaimType && roleClaims.Any())
            {
                foreach (var roleClaim in roleClaims)
                {
                    identity.RemoveClaim(roleClaim);
                    identity.AddClaim(new Claim(ClaimsIdentity.DefaultRoleClaimType, roleClaim.Value, roleClaim.ValueType, roleClaim.Issuer, roleClaim.OriginalIssuer));
                }
            }

            identity.AddClaims(new[]
            {
                new Claim("iat", GetEpocTimeStamp()),
                new Claim("jti", Guid.NewGuid().ToString("N"))
            });

            Lifetime lifetime = new Lifetime(null, null);
            if (data.Properties.IssuedUtc != null || data.Properties.ExpiresUtc != null)
            {
                lifetime = new Lifetime(data.Properties.IssuedUtc != null ? (DateTime?)((DateTimeOffset)data.Properties.IssuedUtc).UtcDateTime : null, data.Properties.ExpiresUtc != null ? (DateTime?)((DateTimeOffset)data.Properties.ExpiresUtc).UtcDateTime : null);
            }

            var handler = new JwtSecurityTokenHandler();
            return handler.CreateToken(issuer, audience, identity, lifetime.Created, lifetime.Expires, signingCredentials).RawData;
        }
        public static void SetIsPersistent(this ClaimsIdentity identity, bool isPersistent)
        {
            var claim = identity.Claims.FirstOrDefault(c => c.Type == PersistentLoginClaimType);

            if (isPersistent)
            {
                if (claim == null)
                {
                    identity.AddClaim(new Claim(PersistentLoginClaimType, Boolean.TrueString));
                }
            }
            else if (claim != null)
            {
                identity.RemoveClaim(claim);
            }
        }
 public JsonResult Escoger(int AgenciaId)
 {
     try {
         var authenticationManager = HttpContext.GetOwinContext().Authentication;
         var identity = new System.Security.Claims.ClaimsIdentity(User.Identity);
         var Claim    = identity.FindFirst(Lib.DataFilters.MustHaveAgencyParam);
         if (Claim != null)
         {
             identity.RemoveClaim(identity.FindFirst(Lib.DataFilters.MustHaveAgencyParam));
         }
         identity.AddClaim(new System.Security.Claims.Claim(Lib.DataFilters.MustHaveAgencyParam, AgenciaId.ToString()));
         authenticationManager.AuthenticationResponseGrant =
             new AuthenticationResponseGrant(
                 new ClaimsPrincipal(identity),
                 new AuthenticationProperties {
             IsPersistent = true
         }
                 );
         return(Json(new { success = true }));
     } catch (Exception ex) {
         return(Json(new { success = false, errors = ex.Message }));
     }
 }
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
            var currentClient = context.ClientId;

            if (originalClient != currentClient)
            {
                context.SetError("invalid_clientId", "Refresh token is issued to a different clientId.");
                return Task.FromResult<object>(null);
            }

            // Change auth ticket for refresh token requests
            var newIdentity = new ClaimsIdentity(context.Ticket.Identity);
            
            var newClaim = newIdentity.Claims.FirstOrDefault(c => c.Type == "newClaim");
            if (newClaim != null)
            {
                newIdentity.RemoveClaim(newClaim);
            }
            newIdentity.AddClaim(new Claim("newClaim", "newValue"));

            var newTicket = new AuthenticationTicket(newIdentity, context.Ticket.Properties);
            context.Validated(newTicket);

            return Task.FromResult<object>(null);
        }
        public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
            var currentClient = context.OwinContext.Get<string>("as:client_id");

            // enforce client binding of refresh token
            if (originalClient != currentClient)
            {
                context.Rejected();
                return;
            }

            // chance to change authentication ticket for refresh token requests
            var newId = new ClaimsIdentity(context.Ticket.Identity);

            newId.RemoveClaim(newId.FindFirst(c => c.Type == "RefreshToken"));
            newId.AddClaim(new Claim("RefreshToken", Guid.NewGuid().ToString()));

            var newTicket = new AuthenticationTicket(newId, context.Ticket.Properties);
            context.Validated(newTicket);
        }
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            //We are reading the client id value from the original ticket, 
            //this is the client id which get stored in the magical signed string, 
            //then we compare this client id against the client id sent with the request, 
            //if they are different we’ll reject this request because we need to make 
            //sure that the refresh token used here is bound to the same client when it was generated.

            var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
            var currentClient = context.ClientId;

            if (originalClient != currentClient)
            {
                context.SetError("invalid_clientId", "Refresh token is issued to a different clientId.");
                return Task.FromResult<object>(null);
            }

            //We have the chance now to add new claims or remove existing claims, 
            //this was not achievable without refresh tokens, then we call 
            //“context.Validated(newTicket)” which will generate new access 
            //token and return it in the response body.


            // Change auth ticket for refresh token requests
            var newIdentity = new ClaimsIdentity(context.Ticket.Identity);

            var newClaim = newIdentity.Claims.Where(c => c.Type == "newClaim").FirstOrDefault();
            if (newClaim != null)
            {
                newIdentity.RemoveClaim(newClaim);
            }
            newIdentity.AddClaim(new Claim("newClaim", "newValue"));

            var newTicket = new AuthenticationTicket(newIdentity, context.Ticket.Properties);
            context.Validated(newTicket);

            return Task.FromResult<object>(null);

            //Lastly after this method executes successfully, the flow for the code 
            //will hit method “CreateAsync” in class “SimpleRefreshTokenProvider” 
            //and a new refresh token is generated and returned in the response 
            //along with the new access token.
        }
 private static void CleanUpAllClaimsButEmail(ClaimsIdentity identity)
 {
     foreach (var c in identity.Claims.Where(c => c.Type != ClaimTypes.Email).ToArray())
     {
         identity.RemoveClaim(c);
     }
 }
        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;
        }
        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;
        }
 public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
 {
     if (context.Ticket.Properties.Dictionary["as:client_id"] != context.ClientId)
     {
         context.SetError("invalid_clientId", "Refresh token is issued to a different clientId.");
         return (Task)Task.FromResult<object>((object)null);
     }
     ClaimsIdentity identity = new ClaimsIdentity((IIdentity)context.Ticket.Identity);
     Claim claim = Enumerable.FirstOrDefault<Claim>(Enumerable.Where<Claim>(identity.Claims, (Func<Claim, bool>)(c => c.Type == "newClaim")));
     if (claim != null)
         identity.RemoveClaim(claim);
     identity.AddClaim(new Claim("newClaim", "newValue"));
     AuthenticationTicket ticket = new AuthenticationTicket(identity, context.Ticket.Properties);
     context.Validated(ticket);
     return (Task)Task.FromResult<object>((object)null);
 }
 private static void ChengeItem(ClaimsIdentity claimsIdentity, Claim toChange)
 {
     var newClaim = RewriteAndCreate(toChange);
     claimsIdentity.RemoveClaim(toChange);
     claimsIdentity.AddClaim(newClaim);
 }