【发布时间】:2016-10-27 15:29:32
【问题描述】:
TL;DR
编辑
基本上,我只是想告诉一些功能:好的,我已经亲自检查过这个用户,他没事。现在存储一些关于他的任意数据并为他创建一个会话,允许他访问我的应用程序的某些部分。
类似的东西:
logInUserFrameworkFunction(new UserStruct(int id, string username, RolesEnum[] roles));
而且所有事情都在后台处理,以使[Authorize(Roles = RolesEnum.Admin | RolesEnum.Manager)] 属性起作用。
我可以自己做这个,但我想跳过那部分:D
我正在使用 MVC 和实体框架,现在我想用角色实现简单的用户身份验证。
我的数据库中有User 类/表,看起来像这样:
public class User {
int ID;
string Email;
string Password;
Role Role;
...
}
Role 类看起来像这样:
public class Role {
int ID;
RoleType Type; // this is an Enum
}
public Enum RoleType {
visitor, employee, admin
}
现在,如果存在具有指定用户名和密码的用户,则检查登录控制器很容易,我只是这样做:
[HttpPost]
public ActionResult LogIn(LogIn login) {
// If credentials are valid
if(new UserManager().IsValid(login.Username, login.Password)) {
var user = db.getUserByEmail(login.Username);
...
我可以轻松地将用户 ID 和 Role 存储在会话中,然后通过在每个相关控制器上调用一些 function 来检查凭据,但我想使用一些 C# 和 MVC 功能。
事情是我宁愿用属性来做,但我不知道怎么做。
这是我想象中的样子:
[Roles(RoleType.visitor, RoleType.employee)]
public ActionResult SomeProtectedAction() {
// only employee and visitor can access this,
// others get redirected to where ever
...
}
【问题讨论】:
标签: c# asp.net asp.net-mvc authentication custom-attributes