【问题标题】:Asp.net Identity + Identity is not maintaining in subsequent requestAsp.net Identity + Identity 在后续请求中未维护
【发布时间】:2015-09-04 17:51:00
【问题描述】:

我正在尝试在我的 Web (MVC5) 应用程序中实现 Asp.net Identity。在用户身份验证方法中,我正在对用户进行身份验证,如果用户存在,那么我将在我的应用程序 (Authentication.cs) 中手动创建声明身份和主体。之后,我将 Claims Principal 分配给当前的 HttpContext 和 Thread。所以现在我可以在同一个请求 httpcontext 中看到 Identity。但是,如果我尝试从不同的操作/页面访问 Claims Identity,那么它将在 User.Identity 对象中显示空值,也就是说,在后续请求中不会维护 Identity。

在我的应用程序中,我在 web.config 中设置了 AuthenticationMode="None",因此我从 OWIN Startup 类中删除了 LoginPath 属性。

我不确定我在这里错过了什么,请帮我解决这个问题。

//OWIN startup.cs
[assembly: OwinStartup(typeof(Web.Startup))]
namespace Web
{

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        // For more information on how to configure your application, 
visit http://go.microsoft.com/fwlink/?LinkID=316888
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            CookieSecure = CookieSecureOption.Always
        });

    }
}
}


//Authentication.cs
//After user authentication, setting Thread and http context.
if (user != null)
{
var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;

var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, "username"));
claims.Add(new Claim(ClaimTypes.Email, "username@gmail.com"));
var userIdentity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);

ClaimsPrincipal principal2 = new ClaimsPrincipal(userIdentity);

authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, userIdentity);

var test = HttpContext.Current.User.Identity.IsAuthenticated; //return false


HttpContext.Current.User = principal2;

test = userIdentity.IsAuthenticated; // User Identity is authenticated return true
System.Threading.Thread.CurrentPrincipal = principal2;
test = HttpContext.Current.User.Identity.IsAuthenticated; //return true

}

但如果我重定向到不同的页面/操作,那么 User.Identity.IsAuthenticated 中的值将显示为 false。

谢谢 塞尔瓦库玛

【问题讨论】:

    标签: asp.net-identity identity persistent


    【解决方案1】:

    IsPersistent 属性专门用于determining whether to persist authentication across multiple requests。将其设置为true

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-19
      • 2014-08-29
      • 2016-05-08
      • 1970-01-01
      相关资源
      最近更新 更多