CookieAuthenticationOptions.AuthenticationType用于什么?

Geo*_*uer 6 asp.net authentication cookies asp.net-identity

在我的应用程序的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)
                    ),
    },
});
Run Code Online (Sandbox Code Playgroud)

我从另一个应用程序复制了这个,我只是注意到如果我取消注释该AuthenticationType行,登录成功(我从我的控制器写入的记录器中获得成功消息)但总是重定向回登录屏幕.

CookieAuthenticationOptions文档中

选项中的AuthenticationType对应于IIdentity AuthenticationType属性.可以分配不同的值,以便在管道中多次使用相同的身份验证中间件类型.(继承自AuthenticationOptions.)

我真的不明白这是什么意思,为什么会导致我的登录请求被重定向(成功登录后,不会少),也没有人知道这个选项是有用的.

tra*_*max 5

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

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

    app.UseCookieAuthentication(new CookieAuthenticationOptions {
        LoginPath = new PathString("/Login/"),
        AuthenticationType = "My-Magical-Authentication",
        // etc...
        },
    });
Run Code Online (Sandbox Code Playgroud)

然后签署用户你需要相同的魔术字符串: AuthenticationManager.SignOut("My-Magical-Authentication")

此字符串也会ClaimsIdentity在创建主体时传递.没有AuthenticationType委托人无法进行身份验证,因为:

/// <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);
  }
}
Run Code Online (Sandbox Code Playgroud)

此方法IsAuthenticated用于整个MVC代码库,所有身份验证机制都依赖于此.

理论上,您也可以通过多个提供商登录,一次只签出其中一个,其他提供商仍然可以进行身份​​验证.虽然我从未尝试过这个.

我刚刚发现的另一个用途 - 如果你没有提供CookieName中间件配置,那么Options.CookieName = CookieAuthenticationDefaults.CookiePrefix + Options.AuthenticationType;(参见构造函数中的第二个if语句).

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