FormsAuthentication.SetAuthCookie没有';MVC 5中的t[授权]

本文关键字:中的 授权 MVC 没有 SetAuthCookie FormsAuthentication | 更新日期: 2023-09-27 18:28:04

我创建了一个全新的ASP.NET MVC 5项目,用FormsAuthentication.SetAuthCookie测试[Authorize]属性。我只需在一个操作中设置一个cookie(在我的家庭控制器中):

    public ActionResult About()
    {
        FormsAuthentication.SetAuthCookie("someUser", false);

我限制访问另一个:

    [Authorize]
    public ActionResult Contact()
    {

当我启动我的网页并导航到/home/contact时,我会被正确地重定向到登录页面。然后我转到/home/about,获取我的cookie,然后返回联系人页面。但我仍然被重定向到登录页面——cookie不会对我进行身份验证/授权。

在调试器中,当我多次加载About页面时,HttpContext.User.Identity.IsAuthenticated == false(也就是说,即使在设置了authcookie之后,它也从未将我视为已通过身份验证)。

这里有什么额外的步骤必须做吗?我不应该为基本身份验证设置自己的IPrincipal,是吗?

FormsAuthentication.SetAuthCookie没有';MVC 5中的t[授权]

从web.config删除:

<modules>
  <!--<remove name="FormsAuthenticationModule" />-->
</modules>

或者简单地删除行在web.config 中

EDIT:我不知道MVC5默认新项目已删除Forms Authentication(模块已删除),所以请确保您还检查了原始帖子下DSR的评论以及所有这些。

检查你的web.config并查找身份验证部分,它应该是这样的,

<authentication mode="Forms">
  <forms loginUrl="..." cookieless="UseCookies" />
</authentication>

http://msdn.microsoft.com/en-us/library/1d3t3c61%28v=vs.85%29.aspx

默认的无Cookie值为"UseDeviceProfile",这意味着如果浏览器报告它支持Cookie,则使用Cookie,否则不使用Cookie,并且它使用查询字符串中的值来维护经过身份验证的状态(需要在回发时保留)。

其次,请确保浏览器中的cookie已打开。如果设备/浏览器不支持cookie或它们已关闭,则SetAuthCookie将对url进行更改,但您必须在调用SetAuthCookie后使用…重定向浏览器。。。

FormsAuthentication.RedirectFromLoginPage(String, Boolean)...

该方法在使用SetAuthCookie进行身份验证后将页面重定向到其目的地。RedirectFromLoginPage将在url查询中放入所需的属性,以在回发时维护登录会话。如果你在网站上到处重定向,你需要通过检查当前用户是否使用HttpContext.current.user.Identity.IsAuthenticated.来维护url查询参数,以交叉回发

为了将您的用户发送到登录页面,您应该使用

FormsAuthentication.RedirectToLoginPage()

该方法将向查询字符串添加一个returnUrl参数,稍后的函数"RedirectFromLoginPage"将在经过身份验证后重定向回该参数。

如果阻止对web.config中具有location元素的用户或角色访问路径和资源,则当未通过身份验证的用户尝试访问这些用户或角色时,Forms Authentication会自动处理重定向到登录页的操作。

  <location path="SomeFolderOnYourSite">
    <system.web>
      <authorization>
        <deny users="?"/>
        <allow roles="Administrators"/>
      </authorization>
    </system.web>
  </location>
 <location path="SomeFolderOnYourSite">
<system.web>
  <authorization>
    <deny users="?"/>
    <allow roles="Administrators"/>
  </authorization>
</system.web>

当我使用相同的代码进行小的更改时,它对我来说不起作用——它在**<location path="~/SomeFolderOnYourSite"> <system.web> <authorization> <deny users="?"/> <allow roles="Administrators"/> </authorization> </system.web> </location>** 上起作用

为forms标记的domain属性指定错误的值也可能导致此问题。

<authentication mode="Forms">
  <forms domain="localhost" ... />
</authentication>