微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

asp.net – CookieAuthenticationOptions.AuthenticationType用于什么?

在我的应用程序的Asp.Net Identity Auth中间件设置中我有
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.)

我真的不明白这意味着什么,为什么这会导致我的登录请求被重定向(成功登录后不会更少),以及这个选项对什么有用.

解决方法

这是一个字符串,可以是任何东西.但这是身份验证类型的标识符.您可以拥有多种身份验证类型:您的数据库用户,Google,Facebook等.据我所知,这是在登录添加生成的Cookie的声明.

您在签出用户时需要知道身份验证提供程序.如果您的身份验证中间件定义如下:

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).

我敢肯定有更多地方可以使用它.但最重要的是提供它并与名称保持一致,否则您将在身份验证系统中获得微妙的错误.

原文地址:https://www.jb51.cc/aspnet/246473.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐