Действие аутентификации не работает, перенаправление не работает - PullRequest
0 голосов
/ 22 марта 2020

Обучение аутентификации и авторизации.

У меня есть секретная страница, которую я украсил атрибутом [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");
    }
}

Однако, когда я go до 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 ()?

и, пожалуйста, никаких мнений о безопасности cook ie, это только для целей обучения

1 Ответ

0 голосов
/ 22 марта 2020

выяснил это !!!

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

            });

cookieAuth и CookieAuth .... были опечаткой sh в верхнем регистре, оба должны были совпадать. то есть CookieAuth !!

...