I already have tables with usernames, passwords, and role IDs, so I do not want to use the ASP.NET Membership tables. And I only need a simple login page that asks for username and password, not their pre-built Identity.UI package.
But I do not know how to get Blazor Server to do a basic login for me. I have what I believe should be the basics configured in Startup.cs, such as:
In ConfigureServices:
services
.AddAuthentication(Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
In Configure():
app.UseAuthentication();
app.UseAuthorization();
Normally I would call something like this:
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
principal,
new AuthenticationProperties { IsPersistent = loginData.RememberMe });
And in fact the above does work if I run it from a .cshtml page, but I want this to work as a Blazor component (.razor).
I tried injecting httpContextAccessor but trying to call the SignInAsync method from there resulted in an error about the headers already being set.
I have a .razor Login component which I don't know what to call to do an actual sign in.
@page "/login"
@using Microsoft.AspNetCore.Authentication.Cookies;
@using Microsoft.AspNetCore.Components;
@using System.Security.Claims;
@inject NavigationManager navigationManager
@inject DataAccess.Models.CurrentDataContext db
<h3>Login</h3>
<div>
Email:
<input type="text" @bind="@email" />
</div>
<div>
Password:
<input type="text" @bind="@password" />
</div>
<div>
<button class="btn btn-primary" @onclick="DoLogin">Log In</button>
<span class="text-danger">@loginErrorMessage</span>
</div>
@code {
string email = "";
string password = "";
string loginErrorMessage = "";
protected async Task DoLogin()
{
var emailTrimmed = email.ToLower().Trim();
var user = db.UserAccount.FirstOrDefault(u => u.EmailAddress.ToLower() == emailTrimmed);
if (user != null) //if (user != null)
{
//TODO check password
var claims = new List<Claim> {
new Claim(ClaimTypes.Name, emailTrimmed)
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
//SIGN in the user
///////////////////////////
// WHAT GOES HERE? ////
///////////////////////////
//
navigationManager.NavigateTo("/fetchdata");
}
else
{
loginErrorMessage = "Error logging in.";
}
}
}