InvalidOperationException:没有为方案'CookieSettings'注册任何身份验证处理程序。您忘记调用AddAuthentication()了吗?

时间:2018-09-18 04:54:43

标签: 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?}");
    });
}

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

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

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

1 个答案:

答案 0 :(得分:0)

您应该在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身份验证。 我建议您阅读thisthis