奇怪的MVC4身份验证行为 - 登录后User.Identity.IsAuthenticated为false

时间:2014-03-13 11:35:11

标签: asp.net asp.net-mvc asp.net-mvc-4

我已从可用的MVC4模板创建了 Internet Application 。此模板生成我正在尝试使用的 AccountController 。问题是即使在 WebSecurity.Login()返回true之后, User.Identity.IsAuthenticated 仍然返回false,我不明白为什么。首先我认为它是通过AccountController对 InitializeSimpleMembership 属性进行了较晚的初始化,因此,我将该部分移动到Global.ascx.cs的Application_Start()例程,但它没有任何区别。这是我正在使用的相关代码。

帐户控制器

[HttpPost]
public ActionResult Login(LoginModel model, string returnUrl) {
    if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe)) {

        //Why this should ever return false?
        bool isAuthenticated = User.Identity.IsAuthenticated; 

        //returns false, even when I log in "Admin" role !
        if (User.IsInRole("Admin")) { 
            return RedirectToAction("Index", "Home", new { area = "Admin" });
        }
        ....
}

Global.ascx.cs

public class MvcApplication : System.Web.HttpApplication {
    protected void Application_Start() {
        AreaRegistration.RegisterAllAreas();
        ...
        // Ensure ASP.NET Simple Membership is initialized only once per app start
        LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);

     }

    private class SimpleMembershipInitializer {
        public SimpleMembershipInitializer() {
            ...
        }
    } 
}

msdn文档here指出,如果用户已登录,则返回true。因此,在上面的 AccountController 代码中, User.Identity.IsAuthenticated 应始终返回True,但这不会发生。它返回假。有什么想法吗?

修改

我的主要问题是在成功进行身份验证后,即在 WebSecurity.Login()返回true之后获取给定用户的角色。

修改2

即使我登录“管理员”角色,Roles.IsUserInRole(“Admin”)也会返回false

即使登录“Admin”角色,User.IsInRole(“Admin”)也会返回false。这已在发布的代码中提及 在原帖中。

1 个答案:

答案 0 :(得分:0)

在使用User.Identity.IsAuthenticated正确设置表单身份验证Cookie之前,

FormsAuthentication.SetAuthCookie在您的登录请求中不会返回true。请参阅http://msdn.microsoft.com/en-us/library/twk5762b.aspx

The SetAuthCookie method adds a forms-authentication ticket to either the cookies collection or the URL if CookiesSupported is false. The forms-authentication ticket supplies forms-authentication information to the next request made by the browser. With forms authentication, you can use the SetAuthCookie method when you want to authenticate a user but still retain control of the navigation with redirects.

如果您想查看登录是否成功,请使用WebSecurity.Login的返回值。见http://msdn.microsoft.com/en-us/library/webmatrix.webdata.websecurity.login(v=vs.111).aspx

要检查用户角色,请使用Roles.IsUserInRole()。见http://msdn.microsoft.com/en-us/library/4z6b5d42(v=vs.110).aspx

相关问题