我是新的MVC 3用户,我正在尝试通过SQL数据库进行管理。 首先,我有Customer实体和admin可以通过admin字段定义,这是Customer实体中的布尔类型。 我想只在“产品”页面中访问管理员,而不是普通客户。 我想制作[授权(角色=“管理员”)]而不是[授权]。 但是,我不知道如何才能真正在我的代码中创建管理员角色。 然后在我的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")]
public class ProductController : Controller
{
public ViewResult Index()
{
var product = db.Product.Include(a => a.Category);
return View(product.ToList());
}
}
这些是我的源代码。我需要制作'AuthorizeAttribute'类吗? 如果我必须这样做,我该怎么做呢?你能跟我解释一下吗?我无法理解如何在我的案例中设定特定的角色。 请帮帮我怎么办。感谢。
答案 0 :(得分:2)
我知道这个问题有点老了,但这就是我做类似的事情。我创建了一个自定义授权属性,用于检查用户是否具有正确的安全访问权限:
[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());
}
}
答案 1 :(得分:1)
您的Role.IsInRole使用情况不正确。那是什么的 [授权(Roles =“Admin”)]用于,无需调用它。
在您的代码中,您没有在任何地方设置角色。如果要进行自定义角色管理,可以使用自己的角色提供程序或将它们存储在身份验证令牌中,如下所示:
http://www.codeproject.com/Articles/36836/Forms-Authentication-and-Role-based-Authorization 请注意以下部分:
// 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中的内置成员资格。 使用“互联网应用程序”模板创建一个新的mvc项目,这将全部为您设置。在visual studio中,单击解决方案资源管理器上方的“asp.net配置”图标。您可以在此管理角色并分配角色。