I'm trying to use the authentication cookie for a successful login.
Here it is how I create a cookie authentication
private async Task<IList<string>> CreatingAuthCookie(ApplicationUser user, bool rememberMe)
{
var rolesUser = await _userManager.GetRolesAsync(user);
var claims = new List<Claim>()
{
new Claim(ClaimTypes.Name, user.NameUser),
new Claim(ClaimTypes.Surname, user.LastNameUser),
new Claim(ClaimTypes.Email, user.Email),
new Claim(ClaimTypes.NameIdentifier, user.Id)
};
foreach (var role in rolesUser)
{
claims.Add(new Claim(ClaimTypes.Role, role));
}
var identity = new ClaimsIdentity(claims, "NameCookieIdentity");
var claimsPrincipal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync("NameCookieIdentity", claimsPrincipal, new AuthenticationProperties()
{
IsPersistent = rememberMe,
});
return rolesUser;
}
Here is How it is handled
builder.Services.AddAntiforgery(options => {
options.Cookie.Name = "X-CSRF-TOKEN-NameCookieIdentity";
options.HeaderName = "X-CSRF-TOKEN-NameCookieIdentity";
options.FormFieldName = "X-CSRF-TOKEN-NameCookieIdentity";
});
builder.Services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
builder.Services.AddAuthentication("NameCookieIdentity").AddCookie("NameCookieIdentity", option =>
{
option.Cookie.Name = "NameCookieIdentity";
option.Cookie.HttpOnly = true;
option.ExpireTimeSpan = System.TimeSpan.FromDays(2);
option.SlidingExpiration = true;
option.LoginPath = "/Identity/User/Login";
option.LogoutPath = "/Identity/User/Logout";
option.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
option.SlidingExpiration = true;
});
builder.Services.AddIdentity<ApplicationUser, IdentityRole >(options =>
{
options.SignIn.RequireConfirmedAccount = true;
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireUppercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequiredLength = 8;
options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
options.Lockout.DefaultLockoutTimeSpan = System.TimeSpan.FromHours(1);
options.Lockout.AllowedForNewUsers = true;
options.Lockout.MaxFailedAccessAttempts = 5;
options.SignIn.RequireConfirmedAccount = true;
options.SignIn.RequireConfirmedEmail = true;
options.User.RequireUniqueEmail = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
And here is how I managed the middleware
app.UseHttpsRedirection();
app.UseStaticFiles(new StaticFileOptions()
{
HttpsCompression = Microsoft.AspNetCore.Http.Features.HttpsCompressionMode.Compress,
OnPrepareResponse = (context) =>
{
var headers = context.Context.Response.GetTypedHeaders();
headers.CacheControl = new Microsoft.Net.Http.Headers.CacheControlHeaderValue
{
Public = true,
MaxAge = TimeSpan.FromDays(7)
};
headers.Expires = DateTime.UtcNow.AddDays(7);
}
});
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
and so on..
The problem is: When I'm trying to reach an action inside a controller which is protected by the [Authorize] data annotation, this last one don't gives me the access to go inside.
I can access by only remove the data annotation Authorize on the top of the action.
Last thing.
This is How I access to the data stored inside the cookie.
var userId = HttpContext.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
Even with the a created cookie, by debugging this statement, I can't access to the data inside of the cookie and the var userId is null.
Please help me out and suggest me well staff to manage the authentication as well as possible.
I'm new in stackoverflow so be good with me :)