c# - MVC3 应用程序中的只读用户权限,更改最少

标签 c# asp.net-mvc-3 architecture filter readonly

我的任务是为我们的 ASP.Net MVC3 应用程序创建一个只读用户。 IE。他们可以登录,查看所有数据,但不能更新任何数据。

我已经阅读了很多身份验证文章/框架,例如:Implement secure ASP.NET MVC applications , 或 Fluent Security Configuration , 或 Creating Action Filters in ASP.Net MVC (还有其他一些,我已经失去了链接)。

大多数方法的问题是它们需要对域/应用程序进行重大更改。而且我只有 一天 来实现该功能。

我们有大约 100 个 Controller ,每个 Controller 平均有 4 个操作(主要是 CRUD 操作),并且不可能遍历每个 Controller 。此外,很容易忘记在新代码上添加属性 - 引入错误。

到目前为止,我已经想出了一个全局过滤器,它拒绝所有基于 POST 的操作和 Controller 操作称为“创建”只读用户:

public class ReadOnlyFilter : IActionFilter 
{

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var currentUser = HttpContext.Current.User;
        if (currentUser == null || !currentUser.Identity.IsAuthenticated)
            return; // user is not logged in yet


        if (!currentUser.IsInRole("Readonly")) 
            return; // user is not read-only. Nothing to see here, move on!

        // Presume User is read-only from now on.


        // if action is of type post - deny
        if (filterContext.HttpContext.Request.HttpMethod.ToUpper() == "POST")
        {
            filterContext.HttpContext.Response.Redirect("~/ReadOnlyAccess");
        }

        // if action is "Create" - deny access
        if (filterContext.ActionDescriptor.ActionName == "Create")
        {
            filterContext.HttpContext.Response.Redirect("~/ReadOnlyAccess");
        }

        // if action is edit - check if Details action exits -> redirect to it.
        //TODO get this done ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

        return;
    }


    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        // blah! have to have this here for IActionFilter
    }
}

接下来我计划为发布操作创建属性 [AllowReadOnlyUser],例如更改密码/电子邮件,并在过滤器中允许该操作通过。

我想知道是否有更好的方法来做这种事情?

更新:该应用程序不供公众使用。它在企业界用于跟踪人员、 Assets 和其他无聊的数据。

更新 2:我似乎已经完成了这项任务。一开始就作为 Controller 完成。完整代码和一些解释你can see in my blog .

最佳答案

您可以根据自己的目的使用 System.Web.Mvc.AuthorizeAttribute。创建一个派生自 AuthorizeAttribute 的类并覆盖方法 AuthorizeCore 和 HandleUnauthorizedRequest。在 AuthorizeCore 中,您确定是否允许用户执行某个操作,在 HandleUnauthorizedRequest 中,您确定在不允许用户时显示什么(例如,显示“NotAllowed”-View)。

创建自定义授权属性后,您必须将该属性添加到应受自定义授权保护的所有 Controller 操作。例如,所有 POST 方法。但是,如果有一个应该允许所有用户使用的 POST 方法,您只需不将该属性添加到该 Controller 操作即可。

关于c# - MVC3 应用程序中的只读用户权限,更改最少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12475308/

相关文章:

c# - 网站拼写检查 API

c# - 使用 iTextSharp 将不同尺寸的页面添加到 PDF

c# - 有点想了解 .NET 中的表达式树

c# - 编写新的自定义 mvc4 成员提供程序

cocoa - Cocoa Mac OS X 应用程序中 Controller 对象数量的标准是什么?

c# - 找到包含查询数组所有元素的输入数组的最小窗口

asp.net-mvc - 为多语言 ASP.NET MVC Web 应用程序设置 CurrentCulture 的最佳位置

asp.net-mvc - 如何使用 Autofac 将 "bind"属性添加到操作过滤器?

c# - 依赖注入(inject)类型选择

asp.net-mvc - Web Api - 架构