I'm trying to do a simple user authentication with the following code

public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid) return Page();
            
            //verfiy the credential
            if(Credential.UserName == "admin" && Credential.Password == "password")
            {
                //Creating the security context
                var claims = new List<Claim> {
                    new Claim(ClaimTypes.Name, "admin"),
                    new Claim(ClaimTypes.Email, "[email protected]")
                };

                var identity = new ClaimsIdentity(claims, "MyCookieAuth");
                ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(identity);

                
                await HttpContext.SignInAsync("MyCookieAuth", claimsPrincipal);
                
                return RedirectToPage("/Index");
            }
            return Page();
        }

await HttpContext.SignInAsync throws:

fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1] An unhandled exception occurred while processing the request. InvalidOperationException: No sign-in authentication handlers are registered. Did you forget to call AddAuthentication().AddCookie("MyCookieAuth",...)? . . . at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

3

There are 3 best solutions below

0
diksed On

Try using this code in program.cs class :

builder.Services.AddAuthentication().AddCookie("MyCookieAuth", options =>
{
    options.Cookie.Name = "MyCookieAuth";
});
0
MetroTriesCoding On

In your startup.cs find public void ConfigureServices and make sure it looks like this.

public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication().AddCookie("MyCookieAuth", options =>
        {
            options.Cookie.Name = "MyCookieAuth";
        });
        services.AddRazorPages();
    }
0
Brighton On

In program.cs add this snippet

`builder.Services.AddAuthentication().AddCookie("MyCookieAuth", options => 
{
    options.Cookie.Name = "MyCookieAuth";
});`