【问题标题】:ASP.NET WebApi2/MVC5 cookie authenticationASP.NET Web Api 2/MVC 5 cookie 身份验证
【发布时间】:2014-01-15 11:30:34
【问题描述】:

我正在尝试实现 cookie 身份验证。这是我的登录操作:

public async Task<IHttpActionResult> Login([FromBody]string email)
{
    var user = await UserManager.FindByNameAsync(email);
    Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
    var identity = 
                   await UserManager.CreateIdentityAsync(user,
                   DefaultAuthenticationTypes.ApplicationCookie); 
                   // identity.IsAuthenticated is true, why?
    Authentication.SignIn(identity); // identity is correct (name is user@user.com), i checked it
    // User.Identity.IsAuthenticated is false here
    return Ok();
}

身份验证是:

private IAuthenticationManager Authentication
{
    get
    {
        return HttpContext.GetOwinContext().Authentication;
    }
}

但 User.Identity.Name 仍然为空。我做错了什么?我怎样才能获得经过身份验证的用户?

这是我的 Startup.Auth:

public partial class Startup
{
    static Startup()
    {
        var userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(new MyDbContext()));
        userManager.UserValidator = new UserValidator<IdentityUser>(userManager)
        {
            AllowOnlyAlphanumericUserNames = false,
        };
        UserManagerFactory = () => userManager;
    }

    public static Func<UserManager<IdentityUser>> UserManagerFactory { get; set; }

    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseCookieAuthentication(new CookieAuthenticationOptions());
    }
}

【问题讨论】:

    标签: c# asp.net-mvc-5 asp.net-web-api2


    【解决方案1】:

    尝试像这样设置登录方法

      private IAuthenticationManager AuthenticationManager
            {
                get
                {
                    return HttpContext.GetOwinContext().Authentication;
                }
            }
    


     public async Task<IHttpActionResult> Login([FromBody]string email)
        {
            var user = await UserManager.FindByNameAsync(email);
            Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
            var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
            AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
            return Ok();
        }
    

    【讨论】:

    • 没有帮助。我忘了说我的身份验证是 HttpContext.GetOwinContext().Authentication。更改 isPersistent 也无济于事
    【解决方案2】:

    解决办法是去掉以下代码:

    Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
    

    【讨论】:

      猜你喜欢
      • 2016-06-17
      • 2015-09-17
      • 2015-06-03
      • 2014-06-02
      • 2014-03-20
      • 1970-01-01
      • 1970-01-01
      • 2015-07-20
      • 1970-01-01
      相关资源
      最近更新 更多