【问题标题】:How to add a cookie based authenticationScheme in ASP.NET Core?如何在 ASP.NET Core 中添加基于 cookie 的 authenticationScheme?
【发布时间】:2021-08-20 23:13:53
【问题描述】:

我想在我的控制器类中使用[Authorize] 属性将未登录的用户重定向到我的登录页面。对于身份验证,我想保持简单,只需使用会话变量来跟踪是否有人登录。

我尝试向我的启动类添加身份验证:

services.AddAuthentication()
            .AddCookie(options =>
            {
                options.AccessDeniedPath = new PathString("/Account/SignIn");
                options.LoginPath = new PathString("/Account/SignIn");
                options.LogoutPath = new PathString("/Home/SignOut");
            });

但是当我转到具有[Authorize] 属性的控制器时出现错误:

InvalidOperationException: 没有指定 authenticationScheme,也没有找到 DefaultChallengeScheme。

那么如何设置身份验证方案或使用默认方案?

【问题讨论】:

    标签: c# authentication asp.net-core


    【解决方案1】:

    您需要设置默认的AuthenticationScheme。

    正如docs 所说

    AuthenticationScheme 传递给 AddAuthentication 设置默认值 应用的身份验证方案。

    你的情况

    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(options =>
                {
                    options.AccessDeniedPath = new PathString("/Account/SignIn");
                    options.LoginPath = new PathString("/Account/SignIn");
                    options.LogoutPath = new PathString("/Home/SignOut");
                });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-19
      • 1970-01-01
      • 2016-09-16
      • 1970-01-01
      相关资源
      最近更新 更多