User roles and authorization
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.
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 开发者_如何学Csome 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;
}
}
The repository method IsAdmin could be as simple as a query to check the boolean corresponding to the supplied user's ID. Something like this (please double check if SingleOrDefault()
is necessary or not):
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...
}
When this returns false, your ActionResult will be an HttpUnauthorizedResult which in theory should redirect to the login page.
You should create a custom Membership Provider and check the user isAdmin as part of ValidateUser.
Alternatively if other users are allowed in, use a custom role provider.
The following link is a good place to start
http://theintegrity.co.uk/2010/11/asp-net-mvc-2-custom-membership-provider-tutorial-part-1/
Is your isAdmin column a bit or a byte? It should probably be a bit. You could just create a query that checks the credentials and the IsAdmin column. If a row is returned then the login was successful.
精彩评论