app.UseCookieAuthentication(new CookieAuthenticationOptions { LoginPath = new PathString("/Login/"),//AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,Provider = new CookieAuthenticationProvider { OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<MyUserManager,MyUser>( TimeSpan.FromMinutes(30),(manager,user) => manager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie) ),},});
我从另一个应用程序复制了这个,我只是注意到如果我取消注释AuthenticationType行,登录成功(我从我的控制器写入记录器中的成功消息)但总是重定向回登录屏幕.
在documentation for CookieAuthenticationOptions它说
The AuthenticationType in the options corresponds to the IIdentity AuthenticationType property. A different value may be assigned in order to use the same authentication middleware type more than once in a pipeline.(Inherited from AuthenticationOptions.)
解决方法
您在签出用户时需要知道身份验证提供程序.如果您的身份验证中间件定义如下:
app.UseCookieAuthentication(new CookieAuthenticationOptions { LoginPath = new PathString("/Login/"),AuthenticationType = "My-Magical-Authentication",// etc... },});
然后为用户签名你需要相同的魔术字符串:AuthenticationManager.SignOut(“My-Magical-Authentication”)
在创建主体时,此字符串也会传递给ClaimsIdentity.并且没有AuthenticationType主体无法进行身份验证because:
/// <summary> /// Gets a value that indicates whether the identity has been authenticated. /// </summary> /// /// <returns> /// true if the identity has been authenticated; otherwise,false. /// </returns> public virtual bool IsAuthenticated { get { return !string.IsNullOrEmpty(this.m_authenticationType); } }
此方法IsAuthenticated通过整个MVC代码库使用,所有身份验证机制都依赖于此.
理论上,您也可以通过多个提供商登录,一次只签出其中一个,其他提供商仍然可以进行身份验证.虽然我从未尝试过这个.
我刚刚发现的另一个用途 – 如果你没有在中间件配置中提供CookieName,那么Options.CookieName = CookieAuthenticationDefaults.CookiePrefix Options.AuthenticationType; (see second if statement in constructor).