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

时间:2020-03-22 18:36:31

标签: c# authentication authorization

学习身份验证和授权。

我有一个秘密页面,该页面在控制器中的属性为[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, "Bob@bobm.com"),
            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安全性提出任何意见,这只是出于学习目的

1 个答案:

答案 0 :(得分:0)

发现了!!!

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

            });

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