I have a cookie authentication based core project using the AspNetCore.Authentication.Cookies but I can't seem to make the user to authenticate. I have read similar threads but none of the solutions provided seem useful.
[HttpPost] public async Task<IActionResult> CookieAuth(ITwitterCredentials userCreds) { var claims = new[] { new Claim("AccessToken" , userCreds.AccessToken), new Claim("AccessTokenSecret", userCreds.AccessTokenSecret) }; var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, "CookieAuthentication")); await HttpContext.Authentication.SignInAsync("CookieAuthentication", principal); return Ok(); }
and startup.cs configure method
app.UseCookieAuthentication(new CookieAuthenticationOptions() { AuthenticationScheme = "CookieAuthentication", LoginPath = new PathString("/"), AccessDeniedPath = new PathString("/"), AutomaticAuthenticate = true, AutomaticChallenge = true });
The user does not seem to authenticate as HttpContext.User.Identity.IsAuthenticated
always returns false.
Any idea why this might not be working?
as of .net 2.x, if you're using cookie auth, ensure you include the authenticationScheme, the identity and auth properties.
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, email)); identity.AddClaim(new Claim(ClaimTypes.Name, email)); identity.AddClaim(new Claim(ClaimTypes.Role, "User")); var principal = new ClaimsPrincipal(identity); var authProperties = new AuthenticationProperties { AllowRefresh = true, ExpiresUtc = DateTimeOffset.Now.AddDays(1), IsPersistent = true, }; await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(principal),authProperties); return RedirectToPage("dashboard");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With