InvalidOperationException:没有为方案“CookieSettings”注册身份验证处理程序。您是否忘记调用 AddAuthentication()

ash*_*dam 7 c#

我正在使用 ASP.Net MVC core 2.1 开发一个应用程序,其中不断出现以下异常。

“InvalidOperationException:没有为方案‘CookieSettings’注册身份验证处理程序。注册的方案是:Identity.Application、Identity.External、Identity.TwoFactorRememberMe、Identity.TwoFactorUserId。您是否忘记调用 AddAuthentication().AddSomeAuthHandler?”

我浏览了文章并做了必要的更改,但例外情况仍然相同。我不知道下一步该做什么。

以下是我的startup.cs

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        // This lambda determines whether user consent for non-essential cookies is needed for a given request.
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    services.AddDbContext<Infrastructure.Data.ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection")));

    services.AddDefaultIdentity<IdentityUser>()
        .AddEntityFrameworkStores<Infrastructure.Data.ApplicationDbContext>();

    services.AddSingleton(Configuration);

    //Add application services.
   services.AddTransient<IEmailSender, AuthMessageSender>();
    services.AddTransient<ISmsSender, AuthMessageSender>();
    //Add services
    services.AddTransient<IContactManagement, ContactManagement>();
    services.AddTransient<IRepository<Contact>, Repository<Contact>>();
    services.AddTransient<IJobManagement, JobJobManagement>();
    services.AddTransient<IRepository<Job>, Repository<Job>>();
    services.AddTransient<IUnitManagement, UnitManagement>();
    services.AddTransient<IRepository<Sensor>, Repository<Sensor>>();
    services.AddTransient<IJobContactManagement, JobContactManagement>();
    services.AddTransient<IRepository<JobContact>, Repository<JobContact>>();
    services.AddTransient<IJobContactEventManagement, JobContactEventManagement>();
    services.AddTransient<IRepository<JobContactEvent>, Repository<JobContactEvent>>();
    services.AddTransient<IJobsensorManagement, JobsensorManagement>();
    services.AddTransient<IRepository<JobSensor>, Repository<JobSensor>>();
    services.AddTransient<IEventTypesManagement, EventTypesManagement>();
    services.AddTransient<IRepository<EventType>, Repository<EventType>>();
    services.AddTransient<IJobSensorLocationPlannedManagement, JobSensorLocationPlannedManagement>();
    services.AddTransient<IRepository<JobSensorLocationPlanned>, Repository<JobSensorLocationPlanned>>();
    services.AddTransient<IDataTypeManagement, DataTypeManagement>();
    services.AddTransient<IRepository<DataType>, Repository<DataType>>();
    services.AddTransient<IThresholdManegement, ThresholdManegement>();
    services.AddTransient<IRepository<Threshold>, Repository<Threshold>>();
    services.AddTransient<ISeverityTypeManagement, SeverityTypeManagement>();
    services.AddTransient<IRepository<SeverityType>, Repository<SeverityType>>();
    services.AddTransient<ISensorDataManagement, SensorDataManagement>();
    services.AddTransient<IRepository<SensorData>, Repository<SensorData>>();
    services.AddTransient<ISensorLocationManagement, SensorLocationManagement>();
    services.AddTransient<IRepository<SensorLocation>, Repository<SensorLocation>>();

    services.AddTransient<ISensorStatusTypeManagement, SensorStatusTypeManagement>();
    services.AddTransient<IRepository<SensorStatusType>, Repository<SensorStatusType>>();
    services.AddTransient<IRepository<SensorDataToday>, Repository<SensorDataToday>>();
    services.AddTransient<ISensorDataTodayManagement, SensorDataTodayManagement>();

    services.AddSession();


    services.AddSession(options =>
    {
        options.IdleTimeout = TimeSpan.FromMinutes(20);
    });

    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
           .AddCookie(options =>
           {
               options.LoginPath = "/Account/Login/";
               options.LogoutPath = "/Account/Logout/";
           });

    services.AddAuthentication(options =>
    {
        options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    });


    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseCookiePolicy();

    app.UseAuthentication();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}
Run Code Online (Sandbox Code Playgroud)

登录/signin.cs:

public async Task<IActionResult> Login(LoginViewModel model, ApplicationUser applicationUser, string returnUrl = "/RealTimeChart/Index")
    {
        ViewData["ReturnUrl"] = returnUrl;
        if (ModelState.IsValid)
        {
            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, set lockoutOnFailure: true
            ApplicationUser signedUser = await _userManager.FindByEmailAsync(model.Email);
            if (signedUser != null)
            {
                var result = await _signInManager.PasswordSignInAsync(signedUser.UserName, model.Password, model.RememberMe, lockoutOnFailure: false);
                if (result.Succeeded)
                {
                    //Authorize login user
                    if (!string.IsNullOrEmpty(signedUser.UserName))
                    {
                        await AuthorizeUser(signedUser);
                    }
                    _logger.LogInformation(1, "User logged in.");
                    HttpContext.Session.SetString("UserName", model.Email);
                    int AccountTypeId = _contactManagement.GetContactDetailsByUserId(signedUser.Id).UserAccountTypeId;
                    HttpContext.Session.SetString("AccountTypeId", AccountTypeId.ToString());
                    return RedirectToLocal(returnUrl);
                }
                else
                {
                    if (_userManager.SupportsUserLockout && await _userManager.GetLockoutEnabledAsync(signedUser))
                    {
                        await _userManager.AccessFailedAsync(signedUser);
                    }
                }

                if (result.RequiresTwoFactor)
                {
                    return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
                }
                if (signedUser.LockoutEnd != null)
                {
                    _logger.LogWarning(2, "User account locked out.");
                    return View("Lockout");
                }
                else
                {
                    ViewBag.InvalidPassword = "Password is Invalid";
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return View(model);
                }
            }
            else
            {
                ViewBag.InvalidEmail = "Email  is Invalid";
                return View(model);
            }
        }
        // If we got this far, something failed, redisplay form
        return View(model);
    }
Run Code Online (Sandbox Code Playgroud)

我尝试将登录方法更改为以下但没有成功,非常感谢您的帮助

List<Claim> userClaims = new List<Claim>
                        {
                            new Claim(applicationUser.Id, Convert.ToString(applicationUser.Id)),
                            new Claim(ClaimTypes.Name, applicationUser.UserName),
                            new Claim(ClaimTypes.Role, Convert.ToString(applicationUser.Id))
                        };

        var identity = new ClaimsIdentity(userClaims, CookieAuthenticationDefaults.AuthenticationScheme);
        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,new ClaimsPrincipal(identity));
Run Code Online (Sandbox Code Playgroud)

小智 12

显然,如果您使用services.AddIdentityCore(),则应该使用
signInManager.CheckPasswordSignInAsync()而不是 signInManager.PasswordSignInAsync()因为signInManager.PasswordSignInAsync()只能与 cookie 一起使用。


Lor*_*ori 5

您应该在 Startup.cs 类的 ConsigureServices 方法中添加以下指令。您可以将其添加到方法的开头:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(o =>
            {
                o.Cookie.Name = options.CookieName;
                o.Cookie.Domain = options.CookieDomain;
                o.SlidingExpiration = true;
                o.ExpireTimeSpan = options.CookieLifetime;
                o.TicketDataFormat = ticketFormat;
                o.CookieManager = new CustomChunkingCookieManager();
            });
Run Code Online (Sandbox Code Playgroud)

此代码允许您注册用于 cookie 身份验证的身份验证处理程序。我建议你读这个这个