在Asp.net core的startup.cs文件中获取用户名

3
我正在使用Asp.net Core授权,需要在startup.cs中获取用户名,但我得到了null。
public void ConfigureServices(IServiceCollection services)
{        
    // some code here
    services.AddHttpContextAccessor();
    services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    services.AddHttpContextAccessor();
            services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            Audit.Core.Configuration.Setup()
                .UseEntityFramework(_ => _
                    .AuditTypeMapper(t => typeof(AuditLog))
                    .AuditEntityAction<AuditLog>((ev, entry, entity) =>
                    {
                        var svcProvider = services.BuildServiceProvider();
                        var httpContext = svcProvider.GetService<IHttpContextAccessor>().HttpContext;

                        entity.AuditData = JsonConvert.SerializeObject(entry);
                        entity.EntityType = entry.EntityType.Name;
                        entity.AuditDate = DateTime.Now;
                        entity.AuditUser = httpContext.User.Identity.Name;
                    })
                .IgnoreMatchedProperties(true));
}

应用程序启动在任何其他中间件/处理程序/任何运行之前运行,因此执行启动应用程序的请求的人尚未经过身份验证。 - CodeCaster
你是如何进行身份验证的?你能从令牌中获取用户名吗? - bobek
我认为AuditEntityAction不会在启动时运行,而只有在发生审计事件时才会运行 - 因此您无需担心在启动代码中了解用户。 @Javad,您的代码有任何错误吗? - Grzesiek Danowski
我正在使用asp.net core身份验证,没有出现任何错误。当发生任何插入/更新时,这行代码entity.AuditUser = httpContext.User.Identity.Name;和上面的代码运行,但用户名为空。如果可能的话,我不知道如何从jwt令牌中获取用户名。 - Javad Memariani
我正在使用 asp.net core 的 UserManager API。 - Javad Memariani
1个回答

0
我找到了为什么httpContext.User.Identity.Name始终为空的问题。对于每个发送到服务器的请求,标头都应该有以下Authorization标头:
Key                Value
Authorization      Bearer ZQ0QZFANcPogvA...

没有 Bearer,httpContext 总是 null。访问这个 link 不错。


1
这取决于认证方法,例如如果您使用Windows身份验证,则用户令牌将作为cookie发送。之前您只有匿名请求。 - Grzesiek Danowski

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接