我可以使用ViewBag值来确定可用函数吗?

问题描述:

所以我目前在登录中使用ViewBag设置来确定他们是否可以看到仅管理员的东西。这样做是因为Roles.CreateRole,Membership.CreateUser和Roles.AddUserToRole被禁用,因为我们使用ModelFirst ASP.net。我可以使用ViewBag值来确定可用函数吗?

public ActionResult Login(LoginModel model, string returnUrl) 
    { 
     ViewBag.Admin = false; 
      if (model.IsValid(model.UserName, model.Password)) 
      { 
       ViewBag.Admin = (bool)model.currentLoggedInEmployee.IsAdmin; 
       FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe); 
       return RedirectToAction("Index", "Home"); 
      } 
      else 
      { 
       ModelState.AddModelError("", "Login data is incorrect!"); 
       return View(model); 
      } 
    } 

然后我们简单地使用:

@if (ViewBag.Admin == true) { 
     <li>@Html.ActionLink("Administration", "Index", "Administration")</li> 
    } 

,只显示这些按钮管理员。这工作。

现在我们想要的东西,是为了确保只有管理员可以运行一些功能,通过做类似的事情正常

[Authenticate(Roles="Admin")] 
[HttpPost] 
    public ActionResult Create(FormCollection collection) 
    { 
     // TODO: Add insert logic here 
    } 

但是因为我们没有任何“角色”,我们不能这样做喜欢这个。我们需要使用ViewBag.Admin值来授权人们使用这些功能。问题是,这怎么办?

+0

你是如何处理身份验证? – Alex 2013-05-08 11:37:08

我会推荐自己滚动AuthorizeAttribute,然后从那里确定当前登录的用户是否是管理员。

当您创建身份验证cookie时,请添加一些附加信息(即admin标志),例如

public ActionResult Login(LoginModel model, string returnUrl) 
{ 
    if (model.IsValid(model.UserName, model.Password)) 
    { 
     var ticket = new FormsAuthenticationTicket(1, 
      model.UserName, 
      DateTime.Now, 
      DateTime.Now.AddMinutes(30), 
      model.RememberMe, 
      model.currentLoggedInEmployee.IsAdmin, // user data 
      FormsAuthentication.FormsCookiePath); 

     // Encrypt the ticket. 
     string encTicket = FormsAuthentication.Encrypt(ticket); 

     // Create the cookie. 
     Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)); 

     // Redirect back to original URL. 
     return RedirectToAction("Index", "Home"); 
    } 
    else 
    { 
     ModelState.AddModelError("", "Login data is incorrect!"); 
     return View(model); 
    } 
} 

创建自定义授权属性以根据角色验证登录用户,例如,

public class AdminOnlyAttribute : AuthorizeAttribute 
{ 
    protected override bool AuthorizeCore(HttpContextBase httpContext) 
    { 
     if (httpContext.Current.User.Identity.IsAuthenticated) 
     { 
      var ticket = ((FormsIdentity)User.Identity).Ticket; 
      return (bool)ticket.UserData; 
     } 
     else 
     { 
      return false; 
     } 
    } 
} 

然后装饰你的行动:

[AdminOnly] 
[HttpPost] 
public ActionResult Create(FormCollection collection) 
{ 
    // TODO: add insert logic here 
} 
+0

谢谢你工作完美! – user2107630 2013-05-08 13:56:22

+0

@ user2107630不用担心,只要保持警惕,即使用户权限在会话期间被撤销,他们仍然可以访问管理员操作。最安全的选择是以最新的权限重新从数据库中提取用户。 – James 2013-05-08 14:00:12