以下是在Blazor Server端上实现身份验证但无需使用Identity模板的示例代码:
创建名为Login.razor的组件,并添加以下代码:
@page "/login"
Login
@code {
private LoginModel loginModel = new LoginModel();
private async void HandleValidSubmit()
{
var result = await _authService.LoginAsync(loginModel);
if (result.Succeeded)
{
NavigationManager.NavigateTo("/");
}
else
{
// Handle login failure
}
}
}
public class LoginModel
{
[Required(ErrorMessage = "Username is required")]
public string Username { get; set; }
[Required(ErrorMessage = "Password is required")]
public string Password { get; set; }
}
在Startup.cs文件的ConfigureServices方法中添加以下代码:
services.AddScoped();
services.AddScoped();
创建名为CustomAuthenticationStateProvider.cs的类,并添加以下代码:
public class CustomAuthenticationStateProvider : AuthenticationStateProvider
{
private readonly IAuthService _authService;
public CustomAuthenticationStateProvider(IAuthService authService)
{
_authService = authService;
}
public override async Task GetAuthenticationStateAsync()
{
var user = await _authService.GetUserAsync();
if (user != null)
{
var identity = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, user.Username),
}, "apiauth_type");
var principal = new ClaimsPrincipal(identity);
return new AuthenticationState(principal);
}
return new AuthenticationState(new ClaimsPrincipal());
}
public void NotifyAuthenticationStateChanged()
{
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
}
}
上一篇:BlazorServerSide-加载更多50个数据
下一篇:BlazorserversideCookieAuthentication-directlinkworkevenuserisnotauthenticated