Blazor 服务器应用程序可以在用户第一次成功身份验证后触发 OnAuthorizedAsync 方法。您可以在 Blazor 服务器应用程序的 Startup.cs 文件中添加以下代码:
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddScoped();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//...
app.UseAuthentication();
//...
}
public class CustomAuthenticationStateProvider : AuthenticationStateProvider
{
private readonly IHttpContextAccessor _httpContextAccessor;
public CustomAuthenticationStateProvider(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public override async Task GetAuthenticationStateAsync()
{
var authState = await base.GetAuthenticationStateAsync();
if (authState.User.Identity.IsAuthenticated)
{
var claim = authState.User.FindFirst("urn:nhs:profile:id");
if (claim != null)
{
// get user ID and set it to session
var userId = claim.Value;
var httpContext = _httpContextAccessor.HttpContext;
httpContext.Session.SetString("UserId", userId);
bool isFirstLogin = /* check if the user logged in first time */;
if (isFirstLogin)
{
// do something when the user logs in for the first time
}
}
}
return authState;
}
}
在上面的代码中,我们使用 CustomAuthenticationStateProvider 类来扩展 AuthenticationStateProvider,并在 GetAuthenticationStateAsync 方法中访问 HttpContext 和 Session 对象以获取用户 ID 并将其保存在会话中。接下来,我们可以检查用户是否第一次登录,并执行相应的操作。例如,在这里,我们将其设置为 bool 类型的 isFirstLogin 变量,在后续的代码中使用它来检查并执行操作。