コード例 #1
0
        /// <inheritdoc/>
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            bool isAuthorized = false;

            var principal = principalProvider.GetPrincipal();

            if (principal == null)
            {
                throw new UnexpectedNullException("Principal could not be retrieved.");
            }

            foreach (var role in requirement.RequiredRoles)
            {
                if (principal.IsInRole(role))
                {
                    isAuthorized = true;
                    break;
                }
            }

            if (!isAuthorized)
            {
                string message = string.Concat("One or more roles are missing: ", string.Join(", ", requirement.RequiredRoles));
                Debug.WriteLine(message);
                throw new ForbiddenException(message);
            }
        }
コード例 #2
0
        /// <inheritdoc/>
        public bool IsAuthorized(string ownerId)
        {
            try
            {
                Ensure.ArgumentNotNullOrWhiteSpace(ownerId, nameof(ownerId));

                var principal = principalProvider.GetPrincipal();
                if (principal == null)
                {
                    throw new UnexpectedNullException("Principal could not be retrieved.");
                }

                if (ownerId.Equals(principal.Identity.Name) || principal.IsInRole(RoleType.Administrator))
                {
                    return(true);
                }
            }
            catch (Exception e)
            {
                logger.LogError(e, e.Message);
            }

            return(false);
        }