用户角色和授权 [英] User roles and authorization

查看:571
本文介绍了用户角色和授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我想创建就是当你输入你的登录凭据,你得到一个存取权限管理登录页面。如果你不是一个管理员,你重定向回到登录页面。在我的数据库我有布尔类型的字段:

So I want to create a login page where when you enter your login credentials as a admin you get acces. If you are not a admin you get redirected back to the login page. In my database I have a field of boolean type:

isAdmin <--datatype(byte")

那么如何才能最好的方式做到这一点?我想做到这一点的存储库模式方式,因为它变得更容易进行单元测试即可。

So how can you the best way do this?! I would like to do this in the repository pattern way as it gets easier to unit test it then.

我有这样的GOOGLE了很多,开始得到对此事有点迷茫。有多少类,模型等我应该有?我猜一个控制器会做。任何人有什么好主意?我读过一些关于对用户角色DCI模式,但它基本上是唯一的检查布尔在数据库中也许是矫枉过正?感谢所有的反馈。

I have googled this a lot and starting to get a bit confused on the matter. How many classes, models etc should I have?! I'm guessing one controller would do. Anyone got any good ideas?! I've read some on the DCI pattern about user roles but as it basically "only" to check that boolean in the database maybe it is overkill? Thankful for all feedback.

推荐答案

如果我理解正确的话,我也有类似的问题。它是您不使用默认的成员资格提供程序(至少是)从你的问题似乎。我也没有。所以我所做的就是创建一个新的授权属性。你的情况可能是这个样子:

If I understand correctly, I had a similar issue. It seems from your question that you are not using the default membership provider (at least as is). I didn't either. So what I did was create a new authorization attribute. In your case it could look something like this:

public class AdminOnlyAttribute : AuthorizeAttribute {
    IUserRepository _UserRepository;

    public SimpleUser SimpleUser { get; set; }

    public AdminOnlyAttribute() {
        _UserRepository = new SqlUserRepository(new DbContext());
    }

    protected override bool AuthorizeCore(HttpContextBase httpContext) {
        bool baseAuthorized = base.AuthorizeCore(httpContext);
        if (!baseAuthorized) {
            return false;
        } 

        //Here you use your repository to check if a user is an admin or not
        bool isAdmin = _UserRepository.IsAdmin(int.Parse(httpContext.User.Identity.Name));

        if (!isAdmin) {
            return false;
        }

        return true;
    }
}

信息库的方法IsAdmin可能是简单的查询,检查相应于提供用户的ID布尔。像这样的东西(请仔细检查,如果的SingleOrDefault()是必要与否):

public bool IsAdmin(int userID) {
    bool isAdmin = (from user in db.Users
                    where user.ID == userID
                    select user.isAdmin).SingleOrDefault();
    return isAdmin;
}

然后用这个在动作你要像这样:

And then use this in the action you want like so:

[AdminOnly]
public ActionResult Index(){
    //Code here...
}

在此返回false,你的ActionResult将是一个HttpUnauthorizedResult这在理论上应该重定向到登录页面。

When this returns false, your ActionResult will be an HttpUnauthorizedResult which in theory should redirect to the login page.

这篇关于用户角色和授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆