Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core Cookie Authentication SignInAsync not working

Tags:

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?

like image 572
KeykoYume Avatar asked Jul 14 '17 10:07

KeykoYume


1 Answers

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"); 
like image 74
George Rios Avatar answered Nov 25 '22 18:11

George Rios