InvalidOperationException:没有为方案"CookieSettings"注册身份验证处理程序。你忘了调用 AddAuthentication()



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

"无效操作异常:没有为方案'CookieSettings'注册身份验证处理程序。注册的方案是:Identity.Application,Identity.External,Identity.TwoFactorRememberMe,Identity.TwoFactorUserId。您是否忘记调用 AddAuthentication((。AddSomeAuthHandler?">

我浏览了文章进行了必要的更改,但例外情况保持不变。我不知道下一步该怎么做.

以下是我的创业公司.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?}");
});
}

登录/登录.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);
}

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

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

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

您应该在类 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();
});

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

在程序中.cs (对于 .NET 核心 7 或 8

(
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromHours(10);
options.LoginPath = "/Auth/Login";
options.AccessDeniedPath = "/Auth/AccessDenied";
});

应用之前。使用授权((;和应用后。使用路由((;使用应用程序。UseAuthentication((;:

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

相关内容

最新更新