Как решить ошибку: InvalidOperationException: No authenticationScheme was specified, and there was no DefaultSignInScheme found?

Рейтинг: 0Ответов: 1Опубликовано: 10.05.2023

Осуществляю авторизацию на сайте через Telegram, но после авторизации вылетает вот такая ошибка:

System.InvalidOperationException: No authenticationScheme was specified, and there was no DefaultSignInScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action<AuthenticationOptions> configureOptions).
   at Microsoft.AspNetCore.Authentication.AuthenticationService.SignInAsync(HttpContext context, String scheme, ClaimsPrincipal principal, AuthenticationProperties properties)
   at Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler`1.HandleRequestAsync()
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Ошибка возникает после выполнения метода:

protected override async Task<HandleRequestResult> HandleRemoteAuthenticateAsync()
        {
            if (!await _antiforgery.IsRequestValidAsync(Context))
                return HandleRequestResult.Fail("Antiforgery validation failed.");

            var state = Request.Query["state"];
            var properties = Options.StateDataFormat.Unprotect(state);
            var origin = new Uri(Request.Form[Options.OriginFieldName].First());
            var userData = DecodeUserData(Request.Form);
            if (!long.TryParse(userData[DataCheckKeys.AuthTime], out var longAuthTime))
            {
                Logger.LogInformation("Authorization time not found.");
                return HandleRequestResult.Fail("Verification failed.", properties);
            }

            var authTime = DateTimeOffset.FromUnixTimeSeconds(longAuthTime);
            if (authTime + TimeSpan.FromMinutes(-5) > _clock.UtcNow ||
                authTime + TimeSpan.FromMinutes(5) < _clock.UtcNow)
            {
                Logger.LogInformation("Time provided by is not without an acceptable range.");
                return HandleRequestResult.Fail("Verification failed.", properties);
            }

            var generatedHash = GenerateHash(userData);
            if (!generatedHash.Equals(userData[DataCheckKeys.AuthHash]))
            {
                Logger.LogInformation("Hash verification failed.");
                return HandleRequestResult.Fail("Verification failed.", properties);
            }

            var identity = new ClaimsIdentity(TelegramAuthenticationDefaults.ClaimsIssuer);
            var ticket = CreateTicket(identity, properties, userData);

            return ticket == null ? HandleRequestResult.Fail("Failed") : HandleRequestResult.Success(ticket);
        }

В Startup.cs вроде бы всё прописал:

 public void ConfigureServices(IServiceCollection services)
        {
            //В своём проекте правильно указал токен и имя бота
            services.AddAuthentication()
               .AddTelegram(options => options.ApiToken = "Токен бота")
               .AddTelegramUI(options => options.BotUserName = "Имя бота");

            services.AddDistributedMemoryCache();

            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromMinutes(30);
                options.Cookie.HttpOnly = true;
                options.Cookie.IsEssential = true;
            });

            services.AddRazorPages();
            services.AddControllers();
        }

       
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

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

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });

        }

Ответы

▲ 0Принят

Ошибка указывает на то, что схема аутентификации по умолчанию не задана или не найдена. Чтобы решить эту проблему, нужно задать схему аутентификации по умолчанию в Startup.cs =>

Задайте схему аутентификации по умолчанию в вызове метода services.AddAuthentication(). Например, вы можете добавить вызов метода AddCookie с установкой схемы аутентификации по умолчанию на Cookies.

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddTelegram(options => options.ApiToken = "токен")
        .AddTelegramUI(options => options.BotUserName = "имя_бота")
        .AddCookie();

Если вы не будете указывать схему аутентификации по умолчанию, будет выброшено исключение InvalidOperationException.