MVC 3授权自定义角色
-
11-12-2019 - |
题
我是新的MVC 3用户,我正在尝试通过SQL数据库制作管理员。 首先,我拥有客户实体,可以通过管理字段定义admin,该字段是客户实体中的布尔类型。 我想仅在产品页面中访问管理员,而不是正常客户。 我想制作[授权(角色=“admin”))而不是[授权]。 但是,我不知道如何在我的代码中创建管理员角色。 然后在我的homeController中写了这个代码。
public class HomeController : Controller
{
[HttpPost]
public ActionResult Index(Customer model)
{
if (ModelState.IsValid)
{
//define user whether admin or customer
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["rentalDB"].ToString());
String find_admin_query = "SELECT admin FROM Customer WHERE userName = '" + model.userName + "' AND admin ='true'";
SqlCommand cmd = new SqlCommand(find_admin_query, conn);
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
//it defines admin which is true or false
model.admin = sdr.HasRows;
conn.Close();
//if admin is logged in
if (model.admin == true) {
Roles.IsUserInRole(model.userName, "admin"); //Is it right?
if (DAL.UserIsVaild(model.userName, model.password))
{
FormsAuthentication.SetAuthCookie(model.userName, true);
return RedirectToAction("Index", "Product");
}
}
//if customer is logged in
if (model.admin == false) {
if (DAL.UserIsVaild(model.userName, model.password))
{
FormsAuthentication.SetAuthCookie(model.userName, true);
return RedirectToAction("Index", "Home");
}
}
ModelState.AddModelError("", "The user name or password is incorrect.");
}
// If we got this far, something failed, redisplay form
return View(model);
}
.
和dal类是
public class DAL
{
static SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["rentalDB"].ToString());
public static bool UserIsVaild(string userName, string password)
{
bool authenticated = false;
string customer_query = string.Format("SELECT * FROM [Customer] WHERE userName = '{0}' AND password = '{1}'", userName, password);
SqlCommand cmd = new SqlCommand(customer_query, conn);
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
authenticated = sdr.HasRows;
conn.Close();
return (authenticated);
}
}
.
最后,我想自定义[授权(角色=“admin”)]
[Authorize(Roles="admin")]
public class ProductController : Controller
{
public ViewResult Index()
{
var product = db.Product.Include(a => a.Category);
return View(product.ToList());
}
}
.
现在是我的源代码。我是否需要制作'专制的课程吗? 如果我必须这样做,我该怎么做?你能解释一下吗?我无法理解如何在我的情况下设置特定的角色。 请帮助我怎么办。谢谢。
解决方案
您的角色.Isinrole使用不正确。那是什么 [授权(授权(角色=“管理员”)]用于,无需调用它。
在代码中,您不会在任何地方设置角色。如果您想做自定义角色管理,您可以使用自己的角色提供程序,或将它们存储在auth令牌中,如此所示:
http://www.codeproject.com/文章/ 36836 /表格认证 - 基于角色的授权 注意:
// Get the stored user-data, in this case, user roles
if (!string.IsNullOrEmpty(ticket.UserData))
{
string userData = ticket.UserData;
string[] roles = userData.Split(',');
//Roles were put in the UserData property in the authentication ticket
//while creating it
HttpContext.Current.User =
new System.Security.Principal.GenericPrincipal(id, roles);
}
}
.
然而,这里更容易的方法是在ASP.NET中使用内置的成员资格。 使用“Internet应用程序”模板创建一个新的MVC项目,这一切都可以为您设置。在Visual Studio中,单击“解决方案资源管理器上方的”ASP.NET配置“图标。您可以在此处管理角色并向角色分配。
其他提示
我知道这个问题有点旧,但这是我如何做类似的东西。我创建了一个自定义授权属性,即我用于检查用户是否具有正确的安全访问权限:
[System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = false, Inherited = true)]
public sealed class AccessDeniedAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
// Get the roles from the Controller action decorated with the attribute e.g.
// [AccessDeniedAuthorize(Roles = MyRoleEnum.UserRole + "," + MyRoleEnum.ReadOnlyRole)]
var requiredRoles = Roles.Split(Convert.ToChar(","));
// Get the highest role a user has, from role provider, db lookup, etc.
// (This depends on your requirements - you could also get all roles for a user and check if they have the correct access)
var highestUserRole = GetHighestUserSecurityRole();
// If running locally bypass the check
if (filterContext.HttpContext.Request.IsLocal) return;
if (!requiredRoles.Any(highestUserRole.Contains))
{
// Redirect to access denied view
filterContext.Result = new ViewResult { ViewName = "AccessDenied" };
}
}
}
.
现在用自定义属性装饰控制器(您还可以装饰单个控制器操作):
[AccessDeniedAuthorize(Roles="user")]
public class ProductController : Controller
{
[AccessDeniedAuthorize(Roles="admin")]
public ViewResult Index()
{
var product = db.Product.Include(a => a.Category);
return View(product.ToList());
}
}
. 不隶属于 StackOverflow