gpt4 book ai didi

asp.net - MVC 3 授权自定义角色

转载 作者:行者123 更新时间:2023-12-02 15:22:06 25 4
gpt4 key购买 nike

我是 MVC 3 新用户,我正在尝试通过 SQL 数据库进行管理。首先,我有客户实体,可以通过管理字段定义管理,该字段是客户实体中的 bool 类型。我只想在产品页面中访问管理员,而不是在普通客户中。我想制作 [Authorize(Roles="admin")] 而不是 [Authorize]。但是,我不知道如何在我的代码中真正发挥管理员角色。然后在我的 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);
}
}

最后,我想自定义[Authorize(Roles="admin")]

[Authorize(Roles="admin")]
public class ProductController : Controller
{
public ViewResult Index()
{
var product = db.Product.Include(a => a.Category);
return View(product.ToList());
}
}

这些是我现在的源代码。我需要创建“AuthorizeAttribute”类吗?如果我必须这样做,我该怎么做?你能给我解释一下吗?我不明白如何在我的案例中设定特定的角色。请帮帮我,我该怎么办。谢谢。

最佳答案

我知道这个问题有点老了,但我是这样做的。我创建了一个自定义授权属性,用于检查用户是否具有正确的安全访问权限:

[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" };
}
}
}

现在用自定义属性装饰 Controller (您也可以装饰单个 Controller 操作):

[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());
}
}

关于asp.net - MVC 3 授权自定义角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9658933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com