1

在 .NET MVC 4 的第一步中,我正在创建一个网站,并且我想实现用户身份验证/授权。

在我的实现中,我希望能够将控件链接到角色。例如,如果我的系统中有 2 个角色:管理员和用户,则在某些观点中说我有 3 个输入:

            <input class="search-field rounded" id="field1" type="text"/>
            <input type="submit" name="submit"/>

            <input class="search-field rounded" id="field2" type="text"/>
            <input type="submit" name="submit"/>

            <input class="search-field rounded" id="field3" type="text"/>
            <input type="submit" name="submit"/>

我希望管理员能够查看和编辑此视图中的所有 3 个字段,但用户应该只能看到其中的 2 个,并且能够编辑其中一个(这只是一个示例)。

所以基本上,我希望能够为控件定义权限,并且一个角色应该由一组权限组成(如果你能想到更好的方法,我很想听听)。

所以这些是我的限制,我看到很多与该主题相关的软件包(例如Fluent SecuritySecurity Guard),但我不太确定哪个最能解决我的挑战。

是否有克服这种需求的最佳实践?

非常感谢任何帮助。

4

3 回答 3

2

idlehands23 展示了您如何访问和检查角色,但我猜您想在视图级别使用此功能。

Within an action method, I usually pass HttpContext.User into the ViewBag or in the case of a strongly typed view you can pass the principal into your model and parse these values out as you wish. Then pass the model to the view like so.

return View(new ModelClass(HttpContext.User))

From here you can add additional code into the view logic to parse/check the roles and render the html with greater specificity using for example:

If (Model.User.IsInRole("Admin"))
{
    //Render admin controls
    //...
}
else
{
   //Render User Controls
   //...
}

Using the [Authorize(Role="Admin||User")] attribute on your action method would restrict access to an entire group of users. In such a case you would need two action methods and one or possibly two distinct views to render the content. However if you just want to limit it to ANY authorized user you can do like so:

    [Authorize]
    public ActionResult Index(){}

Then you can implement the logic at the view level with the certainty that they are authorized.

于 2013-02-15T20:40:28.757 回答
1

我是这样做的:

//In Controller
ViewBag.Roles = Roles.GetRolesForUser(User.Identity.Name);//viewbag because I'm assuming this isn't what you want to strongly type to your page.

//In View
@{
  var roles = (Roles)ViewBag.Roles;
} 
if(roles.contains("admin')) //put whatever you want in place of "admin"
{
    //do something
}

在您的控制器中,您可以通过这种方式访问​​某些视图或部分视图//如果您需要在控制器中。
[Authorize(Roles = "Admin, ImportExport, Search")] //这只是为了安全 public ActionResult 不管(){} *我使用剃刀。如果不是,请用 <% %> 替换 @。

于 2013-02-15T20:24:28.273 回答
0

I ended up creating my own custom membership provider and role provider.

In my Role Provider I added a method

public bool UserHasPermission(string username, string permission) {...}

And in my view I'm doing:

@{
    var roleProvider = Roles.Provider as MyCustomRoleProvider;
    bool addressEditPermission = roleProvider.UserHasPermission(User.Identity.Name, "addressEditPermission");
}

Then I can manipulate my control:

@Html.TextBoxFor(model => model.Name, new { @readonly = addressEditPermission })

You just need to make sure your control has overloads that take HTML attributes.

I hope this helps someone..

于 2013-02-20T10:13:06.647 回答