I am creating CookieAutentecation signin for my Web API.
I have read and followed the official article here and I have done everything correctly as far as I am concerned.
But when I put breakpoints in my controllers and inspect HttpContext.User, everything is always null, no Username, no claims, nothing.
What else do I need to make this work? Are additional steps needed for Web API vs MVC app?
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, act => {
act.LoginPath = "/api/login";
act.AccessDeniedPath = "/api/login";
act.SlidingExpiration = true;
});
services.AddControllers();
services.AddServices(); // <- Own app domain services
services.AddDataAccess(); // <- Own app domain data access
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCors(
options => options.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
api/login
var user = new SecurityUser()
{
UserID = 123,
CompleteName = "Test user",
FirstName = "Test",
Email = "[email protected]"
};
var identity = user.ToClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, 123);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), new AuthenticationProperties()
{
AllowRefresh = true,
ExpiresUtc = DateTime.UtcNow.AddDays(7),
IsPersistent = true,
});
ToClaimsIdentity extension method:
public static ClaimsIdentity ToClaimsIdentity(this SecurityUser user, string authenticantionType, int auditUserID)
{
var claims = new List<Claim>()
{
new Claim(ClaimTypes.NameIdentifier, user.UserID.ToString()),
new Claim(ClaimTypes.Email, user.Email),
new Claim(ClaimTypes.Name, user.FirstName),
new Claim(SecurityUserClaimTypes.AuditUserID, auditUserID.ToString())
};
var identity = new ClaimsIdentity(claims, authenticantionType);
return identity;
}
Any help would be greatly appreciated.

[Authorize]to your controllers?[Authorize]checked theUser.IsAuthorized- But there is no user at all - So adding[Authorize]to controllers just prevents me from accessing the controller and returns a404api/loginthen (another controller)api/production- This is where I am inspecting theUser.Identity- It's not creating the Cookie at all - When I do F12 dev tools, nothing there either