I'm trying to add authentication/login to my Blazor-server app. I don't want to use the Identity stuff, which setups up pages and a database.
When I did this with razor pages, I could have a page for logging in with code like this:
var claims = new List<Claim>{
new Claim(ClaimTypes.Name, Input.Name),
};
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme, principal);
This would log in using cookies, and I could block access to pages, or show/hide stuff based on the claims or whether you are logged in or not.
Now, if I used Identity it would setup razor pages for the login and user management, but I'm trying to do login functionality from a razor component instead, and I can't really find an approach to this. I can try to inject a HttpContextAccessor and use that:
HttpContext httpContext = HttpContextAccessor.HttpContext;
await httpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme, principal);
But it throws an exception: Unhandled exception rendering component: Headers are read-only, response has already started. System.InvalidOperationException: Headers are read-only, response has already started.
Most of what I can find seem to do the razor page approach.
Is it not possible to login using a razor component?