Bluesight Bluesight - 1 year ago 171
C# Question

Cookie Middleware not setting cookie properly

I tried to use the Cookie Middleware from ASP.NET Core to create a custom authorization as mentioned in the official documentation (

Unfortunately it's not working in my ASP.NET MVC Project, no cookie is set after calling "HttpContext.Authentication.SignInAsync".

Here is my current code:


public void Configure(IApplicationBuilder app, IHostingEnvironment env)

if (env.IsDevelopment())



app.UseCookieAuthentication(new CookieAuthenticationOptions()
AuthenticationScheme = "CookieInstance",
LoginPath = new PathString("/Account/Login/"),
AccessDeniedPath = new PathString("/Account/Forbidden/"),
AutomaticAuthenticate = true,
AutomaticChallenge = true,
CookieSecure = env.IsDevelopment()
? CookieSecurePolicy.None
: CookieSecurePolicy.Always

app.UseMvc(routes =>
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");

Login Controller

public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
if (ModelState.IsValid && model.Email == "")

var claims = new List<Claim> {
new Claim(ClaimTypes.Name, "Kev", ClaimValueTypes.String)

var userIdentity = new ClaimsIdentity(claims, "CookieInstance");

var userPrincipal = new ClaimsPrincipal(userIdentity);

await HttpContext.Authentication.SignInAsync("CookieInstance", userPrincipal,
new AuthenticationProperties
ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
IsPersistent = false,
AllowRefresh = false

return RedirectToLocal(returnUrl);
} else { ... }


It successfully redirects me to correct page, but apparentely no cookie will be set. as for example SignInManager.IsSignedIn(User) is still returning false.

Does anyone have a solution?


Answer Source

If you are trying to use the ASP.NET Identity SignInManager ie


that method is not using the same authentication scheme you defined it is using the authscheme from the default IdentityOptions therefore it would report false, it will not see your auth cookie.

The actual code for that method is like this:

    public virtual bool IsSignedIn(ClaimsPrincipal principal)
        if (principal == null)
            throw new ArgumentNullException(nameof(principal));
        return principal?.Identities != null &&
            principal.Identities.Any(i => i.AuthenticationType == Options.Cookies.ApplicationCookieAuthenticationScheme);

so you could do a similar check with your own auth scheme

note that the Options in that code is IdentityOptions and the Cookies property is the CookieAuthOptions for Identity

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download