1

I have an API that uses Identity Server 4 for User Authentication based on JWT Bearer Access Token.

Now when I Pass in the access_token in my request header I can view the User Details in the User Object in the Controller.

Controller User Property

But if I try to access the System.Security.Claims.ClaimsPrincipal in my DAL it is different to my logged in user.

DAL User Property

This is how I configured Authentication for Identity Server 4 in my Web Project Startup.cs

In ConfigureServices -

services.AddAuthentication("Bearer").AddIdentityServerAuthentication(opt =>
        {
            opt.Authority = "http://auth......";
            opt.RequireHttpsMetadata = true;
            opt.ApiName = "API_NAME";
            opt.NameClaimType = "username";
        });

In Configure

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        #region Identity Server Config

        // Setup Identity Server Options for this API -
        app.UseAuthentication();

        #endregion Identity Server Config
        .....
    }

How do I access my logged in Identity Server user in the DAL?

Dawood Awan
  • 7,051
  • 10
  • 56
  • 119
  • Asp.net core has `IHttpContextAccessor` that can be used to access the requests's `User` directly. You can either pass that as a dependency or extract the user and pass that down. I was avoid using the `ClaimsPrincipal.Current` – Nkosi Oct 31 '18 at 23:07
  • @Nkosi thanks for looking into this - do you know how I can pass it into my DAL/Business layer via Dependency Injection? Passing the User to each and every action in my Business layer would be alot of work. I would rather use DI to inject the User into each object of my business layer. – Dawood Awan Oct 31 '18 at 23:10
  • 1
    add `IHttpContextAccessor` to the service collection. and have the accessor injected where needed. I would create a custom service and abstraction that exposes only the current User IPrincipal and have that injected where needed. – Nkosi Oct 31 '18 at 23:13
  • yes - something like this? https://stackoverflow.com/questions/30055268/how-to-get-microsoft-aspnet-http-httpcontext-instance-in-class-constructor-using – Dawood Awan Oct 31 '18 at 23:15
  • 1
    Yes like Steven's answer. That is exactly what I was referring to. – Nkosi Oct 31 '18 at 23:16
  • Thanks @Nkosi -I'll give it a try – Dawood Awan Oct 31 '18 at 23:18

0 Answers0