C# – No authenticationScheme was specified, and there was no DefaultChallengeScheme found Cookies Authentication

asp.net-coreauthenticationc

I am using the below code for authentication in ASP.NET Core 2.0 using cookies

services
    .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie("MyCookieMiddlewareInstance", options =>
    {
        options.AccessDeniedPath = new PathString("/Account/Login");
        options.LoginPath = new PathString("/Account/Login");
        options.LogoutPath = new PathString("/Account/LogOff");
    });

I am getting an error:

No authenticationScheme was specified, and there was no DefaultChallengeScheme found

The cookies setup is below:

var claims = new List<Claim>
{
    new Claim(ClaimTypes.NameIdentifier, userId.ToString()),
    new Claim(ClaimTypes.Name, userName)
};

var identity = new ClaimsIdentity(claims, "Forms");
identity.AddClaim(new Claim(ClaimTypes.Role, "ADMIN"));
var principal = new ClaimsPrincipal(identity);
HttpContext.Authentication.SignInAsync("MyCookieMiddlewareInstance", principal, new AuthenticationProperties
{
    IsPersistent = isPersistent,
    ExpiresUtc = DateTime.UtcNow.AddYears(1)
});

I did some research and didn't find the solution. Here is a link to the doc I used:

Can anyone please let me know how can I resolve this issue?

Best Answer

authenticationBuilder.AddCookie("MyCookieMiddlewareInstance", …)

This registers a cookie authentication handler using the authentication scheme name "MyCookieMiddlewareInstance". So whenever you are referring to the cookie authentication scheme, you will need to use that exact name, otherwise you will not find the scheme.

However, in the AddAuthentication call, you are using a different scheme name:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)

This registers the CookieAuthenticationDefaults.AuthenticationScheme, which has the constant value "Cookies", as the default authentication scheme. But a scheme with that name is never registered! Instead, there’s only a "MyCookieMiddlewareInstance".

So the solution is to simply use the same name for both calls. You can also just use the defaults, and remove the explicit names; if you don’t have multiple schemes and need more control, there isn’t really a need to explicitly set their names.