【问题标题】:Restricting access to action methods in controller in Asp.net MVC限制对 Asp.net MVC 中控制器中操作方法的访问
【发布时间】:2013-12-08 11:08:25
【问题描述】:

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

[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 并访问他未授权的功能。

提前致谢

【问题讨论】:

    标签: asp.net-mvc authentication authorization


    【解决方案1】:

    我的问题是检查是否有更好的解决方案 用户是否登录并根据它重定向用户登录或 仪表板页面,以便用户无法操作 url 并访问 他没有被授权的功能。

    是的,已经有一个不依赖 ASP.NET 会话的内置方法来执行此操作。它被称为Forms Authentication

    您无需编写任何自定义 Authorize 属性。一旦您验证了用户的凭据,只需设置 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 中。这样,当您的应用程序托管在网络场中时,您无需考虑处理复杂的场景,在这种情况下,您需要使用分布式 ASP.NET 会话。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-27
      • 1970-01-01
      • 2018-10-09
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多