[英]Blazor: Authentication remains false
我的 Startup.cs 文件中有一个中间件,用于检查用户当前的身份验证 state。 但是,在调试时,似乎即使在成功登录后,身份验证仍然是错误的。 我一直在寻找解决方案,其中许多提供的解决方案不起作用或不适用于我的项目。 我想知道是否有人遇到过这个问题,或者可以提供任何关于我如何解决这个问题的见解。 提前致谢
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseHttpsRedirection();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseIdentityServer();
app.UseAuthentication();
app.Use(async (context, next) =>
{
await next.Invoke();
if (context.User.Identity.IsAuthenticated)
{
var username = context.User.Identity.Name;
using (var dbContext = context.RequestServices.GetRequiredService<ApplicationDbContext>())
{
var user = dbContext.Users.Where(u => u.UserName == username).FirstOrDefault();
user.LastAccessed = DateTime.Now;
dbContext.Update(user);
dbContext.SaveChanges();
}
}
});
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapFallbackToFile("index.html");
});
}
您可以尝试将app.UseAuthentication();
在app.UseRouting();
之前像这样:
app.UseHttpsRedirection();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseIdentityServer();
app.UseAuthentication();
app.UseRouting();
这是顺序:
app.UseAuthentication();
app.UseAuthorization();
app.Use(async (context, next) =>
{
await next.Invoke();
if (context.User.Identity.IsAuthenticated)
{
var username = context.User.Identity.Name;
using (var dbContext = context.RequestServices.GetRequiredService<ApplicationDbContext>())
{
var user = dbContext.Users.Where(u => u.UserName == username).FirstOrDefault();
user.LastAccessed = DateTime.Now;
dbContext.Update(user);
dbContext.SaveChanges();
}
}
});
可能不是 OP 所期望的,但这对于将来遇到这个问题的人来说可能会派上用场。 .NET 期望ClaimsIdentity
将AuthenticationType
属性设置为已验证。
ClaimsIdentity.IsAuthenticated
如果 AuthenticationType 属性不是 null 或空字符串,则为 true。
当我制作自定义AuthenticationStateProvider
时,我必须确保设置它:
public class CustomAuthStateProvider : AuthenticationStateProvider
{
public async override Task<AuthenticationState> GetAuthenticationStateAsync()
{
string? authType = null;
// ...
// Without this, it won't be considered authenticated
authType = "Token";
var identity = new ClaimsIdentity(claims, authType);
var state = new AuthenticationState(new ClaimsPrincipal(identity));
return await Task.FromResult(state);
}
}
编辑:我只是仔细查看了 OP 的屏幕截图。 看起来它发生在 API 服务器代码上。 我被blazor-webassembly
标签愚弄了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.