Пример #1
0
        /// <summary>
        /// Cookie auth provider that adds extra role claims on the identity
        /// Role claims are kept in cache and added on the identity on every request
        /// </summary>
        /// <returns></returns>
        private static CookieAuthenticationProvider GetMyCookieAuthenticationProvider()
        {
            var cookieAuthenticationProvider = new CookieAuthenticationProvider();

            cookieAuthenticationProvider.OnValidateIdentity = async context =>
            {
                var cookieValidatorFunc = SecurityStampValidator.OnValidateIdentity <UserManager, ApplicationUser>(
                    TimeSpan.FromMinutes(10),
                    (manager, user) =>
                {
                    var identity = manager.GenerateUserIdentityAsync(user);
                    return(identity);
                });
                await cookieValidatorFunc.Invoke(context);

                if (context.Identity == null || !context.Identity.IsAuthenticated)
                {
                    return;
                }

                // get list of roles on the user
                var userRoles = context.Identity
                                .Claims
                                .Where(c => c.Type == ClaimTypes.Role)
                                .Select(c => c.Value)
                                .ToList();

                foreach (var roleName in userRoles)
                {
                    var cacheKey     = ApplicationRole.GetCacheKey(roleName);
                    var cachedClaims = System.Web.HttpContext.Current.Cache[cacheKey] as IEnumerable <Claim>;
                    if (cachedClaims == null)
                    {
                        var roleManager = DependencyResolver.Current.GetService <RoleManager>();
                        cachedClaims = await roleManager.GetClaimsAsync(roleName);

                        System.Web.HttpContext.Current.Cache[cacheKey] = cachedClaims;
                    }
                    context.Identity.AddClaims(cachedClaims);
                }
            };
            cookieAuthenticationProvider.OnApplyRedirect = ctx =>
            {
                if (!IsApiRequest(ctx.Request))
                {
                    ctx.Response.Redirect(ctx.RedirectUri);
                }
            };
            return(cookieAuthenticationProvider);
        }
Пример #2
0
        public async System.Threading.Tasks.Task <IHttpActionResult> EditClaimsAsync([FromBody] RoleClaimsViewModel viewModel)
        {
            var role = await _roleManager.FindByIdAsync(viewModel.RoleId);

            role.Name = viewModel.RoleName;
            var roleResult = await _roleManager.UpdateAsync(role);

            var roleClaims = await _roleManager.GetClaimsAsync(role.Name);

            // this is ugly. Deletes all the claims and adds them back in.
            // can be done in a better fashion
            foreach (var removedClaim in roleClaims)
            {
                await _roleManager.RemoveClaimAsync(role.Id, removedClaim);
            }

            var submittedClaims = viewModel
                                  .SelectedClaims
                                  .Select(s =>
            {
                var tokens = s.Split('#');
                if (tokens.Count() != 2)
                {
                    throw new Exception(String.Format("Claim {0} can't be processed because it is in incorrect format", s));
                }
                return(new Claim(tokens[0], tokens[1]));
            }).ToList();


            roleClaims = await _roleManager.GetClaimsAsync(role.Name);

            foreach (var submittedClaim in submittedClaims)
            {
                var hasClaim = roleClaims.Any(c => c.Value == submittedClaim.Value && c.Type == submittedClaim.Type);
                if (!hasClaim)
                {
                    await _roleManager.AddClaimAsync(role.Id, submittedClaim);
                }
            }

            roleClaims = await _roleManager.GetClaimsAsync(role.Name);

            var cacheKey = ApplicationRole.GetCacheKey(role.Name);

            System.Web.HttpContext.Current.Cache.Remove(cacheKey);
            return(CCOk(roleClaims));
        }