成功PasswordSignIn后,Current.User.Identity.IsAuthenticated为false - 但并非总是

时间:2015-11-10 13:30:42

标签: c# sql-server visual-studio-2013 webforms entity-framework-6

在登录页面上显然成功运行以下内容后:     var result = signinManager.PasswordSignIn(Username.Text,Password.Text,RememberMe.Checked,shouldLockout:false);

在下一页我检查:      if(HttpContext.Current.User.Identity.IsAuthenticated)             ...

通常 true 。但是,当强制清除浏览器缓存时,用户会像往常一样转发到登录页面,并且signManager结果似乎是“SignInStatus.Success”,但是下一页上的IsAuthenticated现在是 false 。基本上用户根本无法登录,并且没有错误消息。

一旦cookie过期(?),就会出现相同的效果。除非我回收网站/应用程序池,否则似乎无法重新验证用户。

背景

我正在使用Visual Studio 2013 ASP.NET WebApplication项目模板(Web窗体),并选择“个人用户帐户”身份验证选项。然后我按照这个项目的基本方法: Getting Started with ASP.NET 4.5 Web Forms and Visual Studio 2013

设置实体等我发现,当使用SQL Server作为数据存储区时,无论是在身份验证过期还是强行清除浏览器缓存时,都会出现上述问题。我尝试过updatind到最新的Entity Framework(编写本时的6.1.3,使用ASP.NET Identity 2.2.1),更改sql express版本,并更新我能找到的所有其他库。但同样的问题仍然存在。一定是我,来自一个表格会员编码背景 - 最感谢任何帮助,因为我完全陷入困境。

任何相关代码:

protected void LogIn(object sender, EventArgs e)
    {
        if (IsValid)
        {
            // Validate the user password
            var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
            var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();
            var user = manager.FindByName(Username.Text);


            var result = signinManager.PasswordSignIn(Username.Text, Password.Text, RememberMe.Checked, shouldLockout: false);
            // If username and password is correct check if account is activated.

            if (result == SignInStatus.Success)
            {
                if (!user.EmailConfirmed && result == SignInStatus.Success)
                {
                    FailureText.Text = "Invalid login attempt. You must have a confirmed email account.";
                    ErrorMessage.Visible = true;
                    return;
                }
            }


            switch (result)
            {
                case SignInStatus.Success:
                    dentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                    break;
                case SignInStatus.LockedOut:
                    Response.Redirect("/Account/Lockout");
                    break;
                case SignInStatus.RequiresVerification:
                    Response.Redirect(String.Format("/Account/TwoFactorAuthenticationSignIn?ReturnUrl={0}&RememberMe={1}", 
                                                    Request.QueryString["ReturnUrl"],
                                                    RememberMe.Checked),
                                      true);
                    break;
                case SignInStatus.Failure:
                default:
                    FailureText.Text = "Invalid login attempt";
                    ErrorMessage.Visible = true;
                    break;
            }
        }
    }

在上面的页面上,重定向到:

protected override void OnLoad(EventArgs e)
    {
        int test = Session.Timeout;
        System.Security.Principal.IPrincipal usr1 = this.Page.User;
        var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
        var user = manager.FindById(User.Identity.GetUserId());

        bool redirectToLogIn = true;

        if (user != null)  //is null when we have the problem
        { 
            var identity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
            if (identity.IsAuthenticated)
            {
                if ((User.IsInRole("administrator") || (User.IsInRole("manager"))))
                {
                    redirectToLogIn = false;
                }
            }
        }

        if (HttpContext.Current.User.Identity.IsAuthenticated) //is false when we have the problem
        {
            System.Security.Principal.IPrincipal usr = this.Page.User;
            if ((usr.IsInRole("administrator") || (usr.IsInRole("manager"))))
            {
                redirectToLogIn = false;
            }
        }
        if (redirectToLogIn)
        {
    Response.Redirect("~/Account/Login/?ReturnUrl=" + HttpUtility.UrlEncode(localTheRetUrl));
         }

...

public void ConfigureAuth(IAppBuilder app)
    {
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)),


                    //Added by me
                     OnException = (context =>
                    {
                        //throw context.Exception;
                    })
            },
            ExpireTimeSpan = TimeSpan.FromMinutes(5)  //For Testing
        });
       app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

    }





public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
    {
        var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
        // Configure validation logic for usernames
        manager.UserValidator = new UserValidator<ApplicationUser>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };

        // Configure validation logic for passwords
        manager.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = false,
            RequireDigit = true,
            RequireLowercase = true,
            RequireUppercase = false,
        };

        // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
        // You can write your own provider and plug it in here.
        manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
        {
            MessageFormat = "Your security code is {0}"
        });
        manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
        {
            Subject = "Security Code",
            BodyFormat = "Your security code is {0}"
        });

        // Configure user lockout defaults
        manager.UserLockoutEnabledByDefault = true;
        manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
        manager.MaxFailedAccessAttemptsBeforeLockout = 5;

        manager.EmailService = new EmailService();
        manager.SmsService = new SmsService();
        var dataProtectionProvider = options.DataProtectionProvider;
        if (dataProtectionProvider != null)
        {
            manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
        }
        return manager;
    }




public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
{
    public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager) :
        base(userManager, authenticationManager) { }

    public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
    {
        return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
    }

    public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
    {
        return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
    }
}

0 个答案:

没有答案