Blazor Webassembly-IdentityServer EventSink和HttpContext

双性恋

我正在使用IdentityServer在ASP.NET Core 3.1中开发Blazor Webassembly应用程序。当IdentityServer处理所有登录,注销,注册等事件时,我试图捕获这些事件,以获得有关用户的一些信息。

为了清楚起见,我试图记住登录日期,并捕获新用户的注册以自动给他们一些角色。

这是我在启动课程中使用的所有服务:

        services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddRoles<IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>();

        services.Configure<IdentityOptions>(options =>
            options.ClaimsIdentity.UserIdClaimType = ClaimTypes.NameIdentifier);

        services.AddIdentityServer()
            .AddApiAuthorization<ApplicationUser, ApplicationDbContext>(options => {
                options.IdentityResources["openid"].UserClaims.Add("name");
                options.ApiResources.Single().UserClaims.Add("name");
                options.IdentityResources["openid"].UserClaims.Add("role");
                options.ApiResources.Single().UserClaims.Add("role");
            });

        // Need to do this as it maps "role" to ClaimTypes.Role and causes issues
        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("role");

        services.AddAuthentication()
            .AddIdentityServerJwt();

我已经实现了IEventSink模式(http://docs.identityserver.io/en/stable/topics/events.html):

public class IdentityServerEventSink : IEventSink
{
    private readonly UserManager<ApplicationUser> userManager;
    private readonly IHttpContextAccessor httpContextAccessor;

    public IdentityServerEventSink(UserManager<ApplicationUser> userManager, IHttpContextAccessor httpContextAccessor)
    {
        this.userManager = userManager;
        this.httpContextAccessor = httpContextAccessor;
    }

    public async Task PersistAsync(Event @event)
    {
        if (@event.Id.Equals(EventIds.ClientAuthenticationSuccess))
        {
            var identity = httpContextAccessor.HttpContext.User;
            var id = httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
            var user = await userManager.Users.FirstOrDefaultAsync(u => u.Id == id);
        }
    }
}

并在startup.cs中:

services.AddHttpContextAccessor();
services.AddTransient<IEventSink, IdentityServerEventSink>();

但是当我进入ClientAuthenticationSuccess事件时,身份始终是匿名的。

我也在中间件中尝试过,但存在相同的问题:

            app.Use(async (context, next) =>
        {
            await next.Invoke();
            //handle response
            //you may also need to check the request path to check whether it requests image
            if (context.User.Identity.IsAuthenticated)
            {
                var userName = context.User.Identity.Name;
                //retrieve uer by userName
                using (var dbContext = context.RequestServices.GetRequiredService<ApplicationDbContext>())
                {
                    var user = dbContext.Users.Where(u => u.UserName == userName).FirstOrDefault();
                    user.LastLogon = System.DateTime.Now;
                    dbContext.Update(user);
                    dbContext.SaveChanges();
                }
            }
        });

你有什么想法 ?我听说HttpContextAccessor在Blazor中是一件坏事。

双性恋

好的,所以在更新之后,中间件委托就可以了!

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();
            if (user != null)
            {
                user.LastLogon = System.DateTime.Now;
                user.LastIpAddress = context.Connection?.RemoteIpAddress?.ToString();

                dbContext.Update(user);
                dbContext.SaveChanges();
            }
        }
    }
});

只需小心配置方法中app.use ...的顺序即可!您需要添加此AFTER app.UseIdentityServer(); app.UseAuthentication(); app.UseAuthorization();

但是很遗憾,IdentityServer的EventSink仍然无法工作,httpContextAccessor.HttpContext.User.Identity始终是匿名的。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

具有IdentityServer4,Asp.Net Core身份和不带实体框架的自定义提供程序的Blazor WebAssembly身份验证

Blazor WebAssembly 发布失败

无法调试Blazor Webassembly

Blazor WebAssembly + Amazon Cognito

Blazor WebAssembly 导航

Blazor WebAssembly 授权

Identity Server脚手架和Blazor WebAssembly

热重载和运行时编译 Blazor Webassembly 托管

配置 blazor wasm 和单独的 identityserver4

Blazor WebAssembly阻止WebApi AllowAnonymous

使用Blazor(即WebAssembly)+ JavaScript

Blazor WebAssembly环境变量

在 Blazor Webassembly 中显示文本

具有AzureAD的Blazor WebAssembly

Blazor webassembly:canvas.toDataUrl()?

Blazor WebAssembly Azure广告验证

在具有身份的Blazor WebAssembly中使用授权角色和策略?

使用Blazor Webassembly和ASP.NET Core安全下载文件

Blazor Webassembly应用程序和检测浏览器功能

为什么blazor dotnet core 3.1的webassembly客户端和共享项目都是netstandard 2.1?

Blazor WebAssembly中使用数据库优先方法进行身份验证和授权

Blazor WebAssembly:设置不同的CurrentUICulture和CurrentCulture时,本地化字符串无法加载

用户在 Blazor Webassembly 身份验证和授权中具有多个角色时的问题?

Blazor WebAssembly:不支持提供的ContentType。

Blazor Webassembly身份验证事件

如何从 Blazor WebAssembly 中的目录读取文件

Blazor Webassembly中的父组件未更新

Blazor WebAssembly中的本地化

Blazor WebAssembly日志记录不遵循SetMinimumLevel