在Asp.net MVC中限制对控制器中操作方法的访问

时间:2013-11-23 15:16:26

标签: asp.net-mvc authentication authorization

我是Asp.net MVC网站开发的新手,我开发了一个使用它的应用程序。在我的应用程序中,我使用自己的身份验证和授权检查如下: 我在这个创建的Login操作方法中创建了Login控制器,如下所示

[HttpPost]
public ActionResult Login(LoginViewModel Info)
{
    if (ModelState.IsValid)
    {
        if (checking username and password exist in DB or not)
        {
            //Adding required values in session 
            Session["username"] = Info.Username;

            //Redirect to dashboard     
        }
        else
        {
            //not found redirect to login page
        }
    }
    return View();
}

现在,当访问管理控制器中的操作方法时,我使用“自定义授权”属性来检查用户是否已登录并拥有方法权限

public class AdminController : Controller
{
    [CustomAuthorize(ValidRole = "Admin")]
    public ActionResult Index()
    {
        return View();
    }
}

为此,我覆盖默认的AuthorizeAttribute,如此

public class CustomAuthorize : AuthorizeAttribute
{
    // Custom property
    public string ValidRole { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext.Session["username"] == null)
        {
            //User is not logged-in so redirect to login page
            return false;
        }
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new RedirectToRouteResult(
        new RouteValueDictionary(
            new
            {
                controller = "Login",
                action = "Login"
            })
        );      
    }
}

这段代码对我来说很好。我的问题是,有没有更好的解决方案来检查用户是否登录,并根据它将用户重定向到登录或仪表板页面,以便用户无法操纵URL并访问他未被授权的功能。 / p>

提前致谢

1 个答案:

答案 0 :(得分:2)

  

我的问题是,有没有更好的解决方案来检查是否   用户是否登录,并根据它将用户重定向到登录或   仪表板页面,以便用户无法操纵URL并获取访问权限   他未获得授权的功能。

是的,已经有一个不依赖于ASP.NET Sessions的内置方法。它被称为Forms Authentication

您无需编写任何自定义授权属性。验证用户凭据后,只需设置FormsAuthentication cookie:

if (checking username and password exist in DB or not)
{
    // Emitting forms authentication cookie
    FormsAuthentication.SetAuthCookie(Info.Username, false);

    //Redirect to dashboard     
}

然后只需使用内置的Authorize属性来修饰受保护的控制器操作:

public class AdminController : Controller
{
    [Authorize(ValidRole = "Admin")]
    public ActionResult Index()
    {
        // At this stage the user is authenticated and has the role Admin.
        // You could get the current username using the User.Identity.Name property
        return View();
    }
}

表单身份验证是无状态的。它不依赖于服务器上的任何状态来跟踪服务器上当前经过身份验证的用户。有关当前用户的信息包含在每个请求中发送的加密表单身份验证cookie中。这样,当您的应用程序托管在Web场中时,您无需考虑处理复杂场景,在这种情况下,您需要使用分布式ASP.NET会话。