如何在ASP.net MVC中限制控制器中某些操作的访问权限

5

我是ASP.net MVC的新手,创建了我的第一个Web应用程序。 在应用程序中,我正在使用数据库身份验证。 我在控制器中创建了登录操作,该操作检查输入的用户名和密码是否存在于数据库中。如果存在,则将所需值放入会话并根据用户的权限将其重定向到相应的页面。否则,将用户重定向到登录页面。就像这样

public ActionResult Login()
{
   if(uservalid)
   {
      //set session values and redirect to dashboard
   }
   else
   {
      //redirect to login
   }
}

在我的应用程序中,有一些功能只能在用户登录后才能访问。我想在用户尝试访问这些功能之前检查用户是否已登录,如果用户未登录或没有权限,则重定向到登录页面或显示一些错误消息。
public ActionResult SomeAction()
{
   //Available only when user is logged-in
}

那么我如何检查用户是否已登录并授予访问权限呢?我读到了Authorize属性,但不知道如何使用它,因为我正在使用数据库身份验证。

4个回答

5

我在操作中使用了[Authorize]和自定义的权限控制属性来限制权限。以下是代码:

 [Authorize]
 [FeatureAuthentication(AllowFeature=FeatureConst.ShowDashboard)]
 public ActionResult Index()
    {

    }

过滤器代码
public class FeatureAuthenticationAttribute : FilterAttribute, IAuthorizationFilter
 {
    public FeatureConst AllowFeature { get; set; }

    public void OnAuthorization(AuthorizationContext filterContext)
    {
        //var featureConst = (FeatureConst)filterContext.RouteData.Values["AllowFeature"];

        var filterAttribute = filterContext.ActionDescriptor.GetFilterAttributes(true)
                                .Where(a => a.GetType() == typeof(FeatureAuthenticationAttribute));
        if (filterAttribute != null)
        {
            foreach (FeatureAuthenticationAttribute attr in filterAttribute)
            {
                AllowFeature = attr.AllowFeature;
            }

            User currentLoggedInUser = (User)filterContext.HttpContext.Session["CurrentUser"];
            bool allowed = ACLAccessHelper.IsAccessible(AllowFeature.ToString(), currentLoggedInUser);
            // do your logic...
            if (!allowed)
            {
                string unAuthorizedUrl = new UrlHelper(filterContext.RequestContext).RouteUrl(new { controller = "home", action = "UnAuthorized" });
                filterContext.HttpContext.Response.Redirect(unAuthorizedUrl);
            }
        }
    }
 }

5
如果您正在使用FormsAuthentication,则不需要使用ASP.NET会话来跟踪当前已验证的用户。

我了解了Authorize属性,但不知道如何在使用数据库验证时使用它。

假设您选择了FormsAuthentication,一旦验证了用户的凭据,您应该设置一个forms身份验证cookie:
public ActionResult Login()
{
   if(uservalid)
   {
      FormsAuthentication.SetAuthCookie("username", false);
      return RedirectToAction("SomeProtectedAction");
   }
   else
   {
      //redirect to login
   }
}

然后:
[Authorize]
public ActionResult SomeAction()
{
   string currentlyLoggedInUser = User.Identity.Name;
}

顺便提一下,如果您在Visual Studio中使用Internet模板创建新的ASP.NET MVC应用程序,您可能需要查看AccountController,它负责验证用户并设置表单身份验证Cookie。当然,您可以将所有Entity Framework内容删除,并根据自己的数据库表实现自己的凭据验证。

你说:“你可以把所有的Entity Framework垃圾扔掉,对自己的数据库表实现自己的凭证验证”.. 有没有一个使用Oracle数据库的示例?我找不到! - Nina

2

你应该创建一个基础控制器,并从基础控制器继承其他控制器,然后检查会话是否为空来验证用户身份。

 public class BaseController : Controller
 {
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (Session["User"]== null)
            {
               filterContext.HttpContext.Response.Redirect("/somepage");
        }

 }

public class SomeController : BaseController
{

}

0

我添加了自定义属性检查权限的答案 :) 请检查它是否有用。 - Murali Murugesan
这取决于CodeWarrior使用注释的情况,但它是有用的。 - Jinal Shah

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接