3

I'm using Asp.net Core Authorization and I need to get username within startup.cs but I got 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));
}
  • The application startup runs before any other middleware/handler/whatever runs, so whoever is executing the request that starts up the application isn't authenticated yet. – CodeCaster Nov 20 '18 at 14:41
  • How are you authenticating? Can you get the username from the token? – bobek Nov 20 '18 at 14:55
  • I suppose that AuditEntityAction is not run on startup, but only when audit event occurs - and therefore you do not have to worry to know user in startup code. @Javad do you have any errors with the code? – Grzesiek Danowski Nov 20 '18 at 15:51
  • I'm using asp.net core authentication and I have no errors. when any insert/update occurs this line entity.AuditUser = httpContext.User.Identity.Name; and codes above run but username is null. idont know how to get username from jwt token if possible. – Javad Memariani Nov 20 '18 at 16:45
  • I'm using UserManager api of as.net core. – Javad Memariani Nov 21 '18 at 07:04

1 Answers1

0

I found the problem why httpContext.User.Identity.Name is always empty. for each request to server the header should have Authorization header like below:

Key                Value
Authorization      Bearer ZQ0QZFANcPogvA...

without Bearer httpContext is always null. not bad to visit this link

  • 1
    It depends on the authentication method, for example if you use windows authentication user token is sended as cookie. Simply previously you have anonymous requests. – Grzesiek Danowski Nov 21 '18 at 12:02