ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,772 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I get a null value for user.Identity.Name, but user.Identity.IsAuthenticated returns the correct value. I get my claim values too.
I have only found a few posts about user.Identity.Name is null, but nothing has solved it.
I have a simple login form:
<form action="cookie" method="post">
<label>Email</label>
<input type="text" name="email" />
<label>Password</label>
<input type="password" name="password" />
<input class="btn btn-primary" type="submit" />
</form>
In Program.cs I have:
builder.Services.AddAuthentication("Cookies")
.AddCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
options.SlidingExpiration = true;
options.AccessDeniedPath = "/Forbidden/";
});
.
.
app.MapControllers();
app.UseAuthentication();
app.UseAuthorization();
My controller looks like this:
[Route("/[controller]")]
[ApiController]
public class CookieController : ControllerBase
{
[HttpPost]
public async Task<ActionResult> Login([FromForm] string email)
{
ClaimsIdentity claimsIdentity = new ClaimsIdentity(new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, email),
new Claim(ClaimTypes.Email, email)
}, "auth");
ClaimsPrincipal claims = new ClaimsPrincipal(claimsIdentity);
await HttpContext.SignInAsync(claims);
return Redirect("/");
}
}
And in the blazor page I have:
[CascadingParameter]
Task<AuthenticationState> authenticationStateTask { get; set; }
.
.
var authState = await authenticationStateTask;
var user = authState.User;
if (user.Identity.IsAuthenticated)
{
string h =
//authMessage = $"{user.Identity.Name} is authenticated.";
}
else
{
//authMessage = "The user is NOT authenticated.";
}
As I said, the authentication works, but I get a null value here for user.Identity.Name.
Is the error somewhere with me, or has Microsoft changed something?
I am using NET 7, Blazor Server
Thanks
I believe the name claim is
new Claim(ClaimTypes.Name, user.Email),