首页 > 解决方案 > 如何解决此“未指定身份验证方案,并且未找到 DefaultChallengeScheme”

问题描述

[![消息错误]] [1]: https://i.stack.imgur.com/ciKCK.png

我的观点是,如果有人在没有登录的情况下进入授权页面,它将被重定向到登录页面。

这是我的代码(.NET Core 3.1):

我的控制器

    [Authorize]
    public IActionResult Username()
    {
        var lstUsername = _dbContext.MT_USERNAME.ToList();
        return View(lstUsername);
    }

我的启动.cs

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<GPServiceDbContext>(options =>
        {
            options.UseSqlServer(xxx);
        });
        services.AddControllersWithViews();

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

    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.UseStatusCodePages(context =>
        {
            var response = context.HttpContext.Response;
            if (response.StatusCode == (int)HttpStatusCode.Unauthorized ||
                response.StatusCode == (int)HttpStatusCode.Forbidden)
                response.Redirect("/Login/Login");
            return Task.CompletedTask;
        });
        app.UseAuthorization();
        app.UseSession();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Login}/{action=Login}/{id?}");
        });
    }

标签: c#asp.net-mvcasp.net-core.net-corevisual-studio-code

解决方案


因为您没有在 ConfigureServices 中配置身份验证服务。以cookie认证为例。需要指定默认的 authenticationScheme。

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = DefaultAuthenticationTypes.ApplicationCookie;
        })
        .AddCookie(DefaultAuthenticationTypes.ApplicationCookie, options =>
        {
            
            options.LoginPath = "/Login";
            options.LogoutPath = "/Logout";
        });

        //...
    }

关于这一点,您也可以参考这些文档。

ASP.NET Core 身份验证

在没有 ASP.NET Core Identity 的情况下使用 cookie 身份验证


推荐阅读