c# – 一个动作可以授权除给定用户角色之外的所有人吗?

c# – 一个动作可以授权除给定用户角色之外的所有人吗?,第1张

概述使用[Authorize]属性可以轻松设置仅由特定用户或角色允许的 *** 作.例如. [Authorize(Roles = "Administrator")]public ActionResult Index(){ ... 但是,当我想要逆时,我遇到了一个问题.有没有办法使用MVC框架功能允许除名称或角色指定的所有经过身份验证的用户? 期望的用法类似于: [DoNotAuthorize(Role 使用[Authorize]属性可以轻松设置仅由特定用户或角色允许的 *** 作.例如.

[Authorize(Roles = "administrator")]public ActionResult Index(){  ...

但是,当我想要逆时,我遇到了一个问题.有没有办法使用MVC框架功能允许除名称或角色指定的所有经过身份验证的用户?

期望的用法类似于:

[DoNotAuthorize(Roles = "RestrictedUser")]public ActionResult Index(){  ...
解决方法 一个相当简单的解决方案是从AuthorizeAttribute类派生并覆盖其AuthorizeCore方法,交换其true / false逻辑.

/// <summary>/// Authorizes any authenticated user *except* those who match the provIDed Users or Roles./// </summary>public class DoNotAuthorizeAttribute : AuthorizeAttribute{    /// <summary>    /// This is effectively a copy of the MVC source for AuthorizeCore with true/false logic swapped.    /// </summary>    /// <param name="httpContext">The http context,which encapsulates all http-specific information about an indivIDual http request.</param>    /// <returns>true if the user is authorized; otherwise,false.</returns>    protected overrIDe bool AuthorizeCore(httpContextBase httpContext)    {        if (httpContext == null)        {            throw new ArgumentNullException("httpContext");        }        IPrincipal user = httpContext.User;        if (!user.IDentity.IsAuthenticated)        {            return false;        }        string[] useRSSplit = SplitString(Users);        if ((useRSSplit.Length > 0) && useRSSplit.Contains<string>(user.IDentity.name,StringComparer.OrdinalignoreCase))        {            return false;        }        string[] rolessplit = SplitString(Roles);        if ((rolessplit.Length > 0) && rolessplit.Any<string>(new Func<string,bool>(user.IsInRole)))        {            return false;        }        return true;    }    /// <summary>    /// This is a direct copy of the MVC source for the internal SplitString method.    /// </summary>    /// <param name="original">The original string to split.</param>    /// <returns>An array of strings.</returns>    internal static string[] SplitString(string original)    {        if (string.IsNullOrWhiteSpace(original))        {            return new string[0];        }        return (from pIEce in original.Split(new[] { ',' })                let trimmed = pIEce.Trim()                where !string.IsNullOrEmpty(trimmed)                select trimmed).ToArray<string>();    }}
总结

以上是内存溢出为你收集整理的c# – 一个动作可以授权除给定用户/角色之外的所有人吗?全部内容,希望文章能够帮你解决c# – 一个动作可以授权除给定用户/角色之外的所有人吗?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1217794.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存