I have implemented claim based authentication in asp.net core 2.0 application. but "
var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;
return null spme time not always.
What I have tried:
Startup.cs:
services.AddAuthentication("TalesSecurityScheme")
.AddCookie("TalesSecurityScheme", options =>
{
options.AccessDeniedPath = new PathString("/Security/Access");
options.Cookie = new CookieBuilder
{
HttpOnly = true,
Name = ".Tales.Security.Cookie",
Path = "/",
SameSite = SameSiteMode.Lax,
SecurePolicy = CookieSecurePolicy.SameAsRequest
};
options.LoginPath = new PathString("/Login/StartPage");
options.ReturnUrlParameter = "RequestPath";
options.SlidingExpiration = true;
});
LoginPage:
List<Claim> claims = new List<Claim>
{
new Claim(ClaimTypes.Name, EncrypterDecrypter.Encrypt(loginEntity.UserName)),
new Claim(ClaimTypes.Email, EncrypterDecrypter.Encrypt(loginEntity.Email)),
new Claim(ClaimTypes.Role, loginEntity.Role),
new Claim(ClaimTypes.Gender, EncrypterDecrypter.Encrypt(loginEntity.Gender)), new Claim(ClaimTypes.Sid, EncrypterDecrypter.Encrypt(loginEntity.UserId))
};
ClaimsIdentity identity = new ClaimsIdentity(claims, "cookie");
ClaimsPrincipal principal = new ClaimsPrincipal(identity);
Thread.CurrentPrincipal = principal;
HttpContext.User = principal;
await HttpContext.SignInAsync(
scheme: "TalesSecurityScheme",
principal: principal,
properties: new AuthenticationProperties
{
ExpiresUtc = DateTime.UtcNow.AddMinutes(_config.Value.CookieTimeout)
});
Home:
var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;
if (identity != null)
{
result = identity.Claims.Where(c => c.Type == ClaimTypes.Email)
.Select(c => c.Value).SingleOrDefault();
}
So SOme time returning null in
identity
variable. Please suggest where i m doing wrong.