我有一个正在开发的MVC4项目。当用户的登录凭据有效时,我会调用FormsAuthentication.SetAuthCookie()
以指示该用户已登录。(我将其包装在一个类中,以便可以为自己的单元测试模拟接口。)
namespace FlashMercy.Shared.Security
{
using System;
using System.Web.Security;
public class Auth : IAuth
{
public void SetAuthCookie(string userId, bool remember)
{
FormsAuthentication.SetAuthCookie(userId, remember);
}
public void Signout()
{
FormsAuthentication.SignOut();
}
}
}
在调试器中,我可以确认该.SetAuthCookie(userId, remember)
行正在执行并且userId
已被填充。
然后,我有一个自定义的授权属性来检查用户是否已登录:
namespace FlashMercy.Shared.Security
{
using System.Web.Mvc;
public class FlashMercyAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Result = new RedirectResult("/");
}
}
}
}
当我调试应用程序时,即使在我已经设置了auth cookie之后,它filterContext.HttpContext.User.Identity.IsAuthenticated
仍然是false
。另外,filterContext.HttpContext.User.Identity.Name
为空。我不确定我在这里缺少什么。
如果您希望查看整个源代码,可以在GitHub上找到它:https : //github.com/quakkels/flashmercy。
代码的问题是您正在使用FormsAuthentication,但没有将其添加到web.config。您的web.config应该包含以下部分:
<system.web>
<authentication mode="Forms"></authentication>
...
</system.web>
基于这种模式Asp.Net了解认证模式应该使用,如窗体,Windows等而且没有设置它Forms
的值-FormsAuthenticationModule
只是忽略.ASPXAUTH饼干从请求。
PS。我已经下载了您的代码,并且在web.config中具有正确的身份验证部分,它可以正常工作并更新HttpContext.User.Identity.IsAuthenticated
为true。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句