BlazorServerside=>AuthenticationwithoutIdentityScaffoldingPOSSIBLE?
创始人
2024-12-21 15:30:24
0

以下是在Blazor Server端上实现身份验证但无需使用Identity模板的示例代码:

  1. 创建自定义登录组件

创建名为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; } }
  1. 在Startup.cs文件中添加Auth服务的依赖注入

在Startup.cs文件的ConfigureServices方法中添加以下代码:

services.AddScoped();
services.AddScoped();
  1. 创建自定义身份验证状态提供程序

创建名为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());
    }
}
  1. 创建自

相关内容

热门资讯

透视教程!hhpoker德州挂... 透视教程!hhpoker德州挂真的有吗,werplan透视挂,学习教程(一贯存在有挂)-哔哩哔哩1、...
透视游戏!aapoker免费透... 透视游戏!aapoker免费透视脚本,xpoker辅助工具,诀窍教程(一贯存在有挂)-哔哩哔哩1)a...
透视大厅!aa poker透视... 透视大厅!aa poker透视软件(透视)开挂辅助器(原来是有挂)-哔哩哔哩1、超多福利:超高返利,...
透视脚本!xpoker辅助工具... 透视脚本!xpoker辅助工具,pokernow辅助工具,方案教程(一贯真的有挂)-哔哩哔哩1、不需...
透视修改器!wepoker透视... 透视修改器!wepoker透视有吗(透视)开挂辅助神器(竟然是有挂)-哔哩哔哩wepoker透视有吗...
透视科技!wejoker透视方... 透视科技!wejoker透视方法,wepoker线上大神,操作教程(确实存在有挂)-哔哩哔哩在进入w...
透视苹果版!wepoker黑侠... 透视苹果版!wepoker黑侠辅助器正版下载,aapoker透视插件,举措教程(切实真的是有挂)-哔...
透视存在!wepoker辅助脚... 透视存在!wepoker辅助脚本(透视)开挂辅助软件(确实存在有挂)-哔哩哔哩1、玩家可以在wepo...
透视辅助!wejoker辅助机... 透视辅助!wejoker辅助机器人,wepoker挂,窍要教程(总是存在有挂)-哔哩哔哩wejoke...
透视私人局!pokemmo手机... 透视私人局!pokemmo手机脚本,wepoker安装教程,经验教程(真是是真的挂)-哔哩哔哩1.p...