Bluesight Bluesight - 1 month ago 28
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 asp.net documentation (https://docs.asp.net/en/latest/security/authentication/cookie.html).

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:

Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}

app.UseStaticFiles();

app.UseIdentity();

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 =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}


Login Controller

[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
if (ModelState.IsValid && model.Email == "test@test.com")
{

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?

thanks

Answer

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

SignInManager.IsSignedIn(User) 

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