简体   繁体   中英

How to solve this “No authenticationScheme was specified, and there was no DefaultChallengeScheme found”

[:[Message error]] [1]: https://i.stack.imgur.com/ciKCK.png

My point is if someone go to Authorize page without login, It will be redirected to the login page.

This is my code (.NET Core 3.1):

My Controller

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

My Startup.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?}");
        });
    }

Because you didn't configure authentication service in ConfigureServices. Take the cookie authentication as an example. An default authenticationScheme need to be specified.

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

        //...
    }

About this, you can also refer to these documents.

ASP.NET Core authentication

Use cookie authentication without ASP.NET Core Identity

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM