MVC roles with custom properties

岁酱吖の 提交于 2019-12-11 08:32:19

问题


I'm looking into how to implement authorization in MVC 4 (.NET 4.5), and have specifically been reading about SimpleMembership. Is there any typical or accepted way in MVC to have roles that have additional properties aside from a name?

For example, suppose you were designing a CMS, and wanted to be able to have a role called something like Writer that let a user make modifications. However, you also want the role to be restrictive to a single page. The only way that I know of to do that would be to have a separate role for each page, where each role might be named something like Writer_<PageID>. Is there any pattern that's nicer than this, or is that pretty much all we can do?

Ideally, I'm wondering if there'd be some way to be able to have something remotely like:

public ActionResult EditPage(Page page) {
    WriterRole role = new WriterRole(page);

    if (!User.IsInRole(role)) {
        return NotAuthorized();
    }

    // Edit...
}

Instead of:

public ActionResult EditPage(Page page) {
    string role = "Writer_" + page.Id;

    if (!User.IsInRole(role)) {
        return NotAuthorized();
    }

    // Edit...
}

回答1:


What I would do is have one Writer role then check the UserId to see if the person owns the editable resource.

[Authorize(Roles = "Writer")]
public ActionResult EditPage(Page page) {
    if (User.UserId == page.UserId) { ... }
}


来源:https://stackoverflow.com/questions/14991274/mvc-roles-with-custom-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!