Owin Authentication.SignIn not working

2019-02-21 16:23发布

问题:

I try to use owin authentication manager to authenticate users but User.Identity.IsAuthenticated is still false.

Startup.cs

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.MapSignalR();
    }
}

Startup.Auth.cs

public partial class Startup
{
    public static Func<UserManager<ApplicationUser>> UserManagerFactory { get; set; }

    public Startup()
    {
        UserManagerFactory = () =>
        {
            var userManager = new UserManager<ApplicationUser>(new CustomUserStore());
            return userManager;
        };
    }

    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            LogoutPath = new PathString("/Account/LogOff"),
            ExpireTimeSpan = TimeSpan.FromDays(7)
        });
    }
}

Some part of authentication action:

private async Task SignInAsync(ApplicationUser user, bool isPersistent)
    {
        var authManager = return HttpContext.GetOwinContext().Authentication;
        authManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
        var identity = await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
        authManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, identity);
    }

The identity creates successfully but SignIn method doesn't sign in a user. What's wrong?

回答1:

It's a very stupid mistake. I have forgotten to call ConfigureAuth method.

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app); // <-- this
        app.MapSignalR();
    }
}