身份验证操作不起作用重定向不起作用

问题描述 投票:0回答:1

学习认证和授权。

我有一个秘密页面,我在控制器中用属性[Authorize]装饰了它,如下所示:

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    [Authorize]
    public IActionResult Secret()
    {
        return View();
    }

    public IActionResult Authenticate()
    {
        var grandmaClaims = new List<Claim>()
        {
            new Claim(ClaimTypes.Name, "Bob"),
            new Claim(ClaimTypes.Email, "[email protected]"),
            new Claim("Grandma.says", "very nice boi")
        };

        var lincenseClaim = new List<Claim>()
        {
            new Claim(ClaimTypes.Name, "Bob "),
            new Claim("DrivingLicense", "A+")
        };

        var grandmaIdentity = new ClaimsIdentity(grandmaClaims, "Grandma Identity");
        var licenseIdentity = new ClaimsIdentity(lincenseClaim, "Government");

        var userPrincipal = new ClaimsPrincipal(new [] {grandmaIdentity});

        HttpContext.SignInAsync(userPrincipal);

        return RedirectToAction("Index");
    }
}

但是当我转到https://localhost:44327/home/secret时,出现此错误:

InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action<AuthenticationOptions> configureOptions).

但是我很确定我已经做了起步时期望的工作才能使它正常工作:

public class Startup
{

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication("cookieAuth")
            .AddCookie("CookieAuth", config =>
            {
                config.Cookie.Name = "Grandmas.Cookie";
                config.LoginPath = "/Home/Authenticate";

            });

        services.AddControllersWithViews();
    }


    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        app.UseAuthentication();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapDefaultControllerRoute();

        });
    }
}

为什么不调用authenticate()操作?

并且请不要对Cookie安全发表任何意见,这只是出于学习目的

c# authentication authorization
1个回答
0
投票

发现了!!!

        services.AddAuthentication("cookieAuth")
            .AddCookie("CookieAuth", config =>
            {
                config.Cookie.Name = "Grandmas.Cookie";
                config.LoginPath = "/Home/Authenticate/";

            });

cookieAuth和CookieAuth ....是一个愚蠢的大写错字,应该都已经匹配。即CookieAuth !!

© www.soinside.com 2019 - 2024. All rights reserved.