I implement ASP.NET Core cookie Authentication In blazor server side. I write simple API Controller with Login endpoint.
When I post to API via postman everything works fine and I become identified and Authorized.
When I post via HttpClient: _http.PostJsonAsync<bool>("api/auth/Login", credentials);
I hit the API endpoint and its run to till end without error but the Authentication State don't change and no cookie is created.
var res = await _http.PostJsonAsync<bool>("api/v1/Auth/Login", credentials);
api:
[AllowAnonymous]
[HttpPost]
[Route("Login")]
public async Task<bool> Login()
{
const string Issuer = "mydomain.com";
var claims = new List<Claim>
{
new Claim("ID", dataTable.Rows[0]["ID"].ToString(), ClaimValueTypes.String, Issuer),
new Claim("FullName", dataTable.Rows[0]["FullName"].ToString(), ClaimValueTypes.String, Issuer),
new Claim("CompanyName", dataTable.Rows[0]["CompanyName"].ToString(), ClaimValueTypes.String, Issuer),
new Claim("Email", dataTable.Rows[0]["Email"].ToString(), ClaimValueTypes.String, Issuer),
};
var userIdentity = new ClaimsIdentity(claims, "User");
var userPrincipal = new ClaimsPrincipal(userIdentity);
await HttpContext.SignInAsync
(
CookieAuthenticationDefaults.AuthenticationScheme,
userPrincipal,
new AuthenticationProperties
{
ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
IsPersistent = false,
AllowRefresh = false
}
);
return true;
}
There are two solution for your problem:
Place a call to the login method in a page that is loading;that is,in the event OnInitAsync, but this is not useful because you probably want it to execute when a button is clicked...
This is the solution you are looking for: Using A Redirect Login Page. This is from the referenced link below:
await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);
Can only be set if we start a new http request. This is achieved by redirecting the user to the page that sets the user.
See full article: Demonstration of Simple Server side Blazor Cookie Authentication [this link is outofdate]