【问题标题】:Multiple authorisation requests多个授权请求
【发布时间】:2012-03-09 10:19:28
【问题描述】:

我对 MVC 还很陌生,甚至还没有真正掌握 [Authorize] 的窍门。基本上,我有一个网站,对于一个区域,要求他们在访问之前提供他们的电子邮件地址、姓名和公司。没有密码,没有注册等。然后会有一个Admin 区域,用户需要使用他们的电子邮件地址和密码登录。

我的问题是,我将如何实施双重授权情况?

还忘了提到,当在Admin 区域时,他们可以将材料上传到他们管理的网站,即比他们目前所在的网站更多。我有一个数据库,其中包含他们管理的站点。该 URL 类似于 /Admin/Site/ 但是一旦他们登录到管理员,我如何确保他们无法进入 /Admin/Site2 其中Site2 不是他们的管理员。

【问题讨论】:

标签: c# asp.net-mvc asp.net-mvc-3 razor


【解决方案1】:

我假设此人可以匿名并下载文件,只要她/他之前提供了详细信息。在这种情况下,请忽略 Authorization 属性并编写您自己的属性。这是一个简单的例子。它依赖于要设置的 cookie。

public class CheckEmailAddressAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var request = filterContext.HttpContext.Request;
        // if the cookie isn't set the a user never provided their details
        if (request.Cookies["mycookiename"] == null)
        {
            // Set it to the correct result, to redirect the user to provide their email address
            filterContext.Result = new ViewResult { ViewName = "GetEmailAddress" };
            filterContext.HttpContext.Response.AppendCookie(new HttpCookie("mycookiename", "true"));
        }
        else
        {
            // Don't do anything, the user already provided their email address
        }

    }
}

并在进行下载的控制器上像这样指定它。

public class DownloadController : Controller
{
    [CheckEmailAddress]
    public ActionResult Download(string name)
    {
        // Implement download
    }    
}

唯一剩下的就是在设置电子邮件地址时设置 cookie。我假设你知道该怎么做。您可能还需要确保您有一些“returnUrl”参数,这样您就可以在用户提供电子邮件地址后将其重定向到下载页面。

编辑

根据 OP,我们不想设置 cookie,除非该人输入他们的详细信息,因此这是更新后的类。

public class CheckEmailAddressAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var request = filterContext.HttpContext.Request;
        // if the cookie isn't set the a user never provided their details
        if (request.Cookies["mycookiename"] == null)
        {
            // Set it to the correct result, to redirect the user to provide their email address
            filterContext.Result = new ViewResult { ViewName = "GetEmailAddress" };
            // filterContext.HttpContext.Response.AppendCookie(new HttpCookie("mycookiename", "true"));
        }
        else
        {
            // Don't do anything, the user already provided their email address
        }

    }
}

【讨论】:

  • 所以,例如,我会在新闻区域内的所有内容上都有 [CheckEmailAddress],但询问其详细信息的页面除外?
  • 另外,在这个例子中,他们所要做的就是进入页面并设置cookie。他们可以被重定向到页面,然后简单地向后导航,然后他们就有了 cookie。
  • 查看我的更新。不应在属性中设置 cookie。
  • 那么,cookie 现在设置在哪里?
  • 这真的取决于你在哪里添加它。您可以将其添加到 GlobalFilters、控制器或操作中。我用的区域不多,因此不知道是否可以为“区域”中的所有控制器注册一个动作过滤器。
猜你喜欢
  • 2021-02-15
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 2019-12-16
  • 2021-12-19
  • 1970-01-01
  • 2020-02-10
相关资源
最近更新 更多