I am using the below code for authentication in ASP.NET Core 2.0 using cookies
services
.AddAuthentication(CookieAuthenticationDefaults.AuthenticationSch
HttpContext.Authentication
is obsolete in ASP.net core 2.0, so instead
HttpContext.Authentication.SignInAsync
use HttpContext.SignInAsync
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.
For those who land on this and leave frustrated, my advice is take a look at the answer to this question: ASP.NET Core 2.0 authentication middleware
Without re-iterating what you find there too much it seems this issue is related to the changes in security between ASP.Net Core 1 and 2. Certainly, the advice there resolved my own issues. It's also worth taking a look at this blog post: https://ignas.me/tech/custom-authentication-asp-net-core-20/ (which I suspect was written based on that SO answer)