'InvalidOperationException: No authentication handler is registered for the scheme 'CookieSettings'.Did you forget to call AddAuthentication()
I am developing an application using ASP.Net MVC core 2.1 where I am continuously getting the following exception.
"InvalidOperationException: No authentication handler is registered for the scheme 'CookieSettings'. The registered schemes are: Identity.Application, Identity.External, Identity.TwoFactorRememberMe, Identity.TwoFactorUserId. Did you forget to call AddAuthentication().AddSomeAuthHandler?"
I went through articles did the necessary changes but exception remains the same. I am unable to figure out what to do next .
following is my 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?}");
});
}
login/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);
}
i tried changing my login method to below but no success, your help is highly appreciated
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));
Solution 1:[1]
You should add the following instructions in the ConsigureServices method in class Startup.cs. You can add this at the beginning of the method:
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();
});
This code let you to register the authentication handler for cookies authentication. I suggest you this read this or this
Solution 2:[2]
Apparently, if you use services.AddIdentityCore()
, you should usesignInManager.CheckPasswordSignInAsync()
as opposed to signInManager.PasswordSignInAsync()
because signInManager.PasswordSignInAsync()
can only be used with cookies.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Gift Ntokozo Mavuso |