Exemple #1
0
        /// <summary>
        /// Called when authorization is required.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            SecurityPrincipal securityPrincipal = filterContext.HttpContext.User as SecurityPrincipal;

            if ((object)securityPrincipal == null || (object)securityPrincipal.Identity == null)
            {
                filterContext.Result           = new HttpUnauthorizedResult($"Authentication failed for user \"{filterContext.HttpContext.User?.Identity.Name}\".");
                filterContext.HttpContext.User = null;
                return;
            }

            // Get current user name
            string username = securityPrincipal.Identity.Name;

            // Verify that the current thread principal has been authenticated.
            if (!securityPrincipal.Identity.IsAuthenticated)
            {
                filterContext.Result           = new HttpUnauthorizedResult($"User \"{username}\" is not authenticated.");
                filterContext.HttpContext.User = null;
            }
            else if (AllowedRoles.Length > 0 && !AllowedRoles.Any(role => securityPrincipal.IsInRole(role)))
            {
                filterContext.Result           = new HttpUnauthorizedResult($"Access is denied for user \"{username}\": minimum required roles = {AllowedRoles.ToDelimitedString(", ")}.");
                filterContext.HttpContext.User = null;
            }
            else
            {
                ThreadPool.QueueUserWorkItem(start => AuthorizationCache.CacheAuthorization(username, SecuritySettingsCategory));
            }
        }
Exemple #2
0
        /// <summary>
        /// Provides an entry point for custom authorization checks.
        /// </summary>
        /// <param name="user">The <see cref="IPrincipal"/> for the client being authorize</param>
        /// <returns>
        /// <c>true</c> if the user is authorized, otherwise, <c>false</c>.
        /// </returns>
        protected override bool UserAuthorized(IPrincipal user)
        {
            SecurityPrincipal securityPrincipal = user as SecurityPrincipal;

            if ((object)securityPrincipal == null)
            {
                return(false);
            }

            // Verify that the current thread principal has been authenticated.
            if (!securityPrincipal.Identity.IsAuthenticated)
            {
                return(false);
            }

            if (AllowedRoles.Length > 0 && !AllowedRoles.Any(role => securityPrincipal.IsInRole(role)))
            {
                return(false);
            }

            ThreadPool.QueueUserWorkItem(start => AuthorizationCache.CacheAuthorization(securityPrincipal.Identity.Name, SecuritySettingsCategory));

            return(true);
        }