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

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

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....