Can I pass logged in windows user to ASP.NET Core Web API?

705 Views Asked by At

I'm building an intranet application where I would like to check the Active Directory username and claims of a user who submits a front end request from a razor page to the back end ASP.NET Core Web API so that I can restrict certain endpoints by job department.

While developing locally, I am able to view my username by using User.Identity.Name in my API endpoint, but only if I call the endpoint using swagger. Submitting a call to the same method from my front end results in a 401 Unauthorized error. Adding the [AllowAnonymous] attribute lets me access the method from the front end, telling me my user is not being sent.

I'm trying to find the best method to automatically (if possible) forward the user accessing the front end directly to the backend request, similar to how accessing the method using swagger works.

I have

builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme).AddNegotiate();
builder.Services.AddAuthorization(options =>
        {
            // By default, all incoming requests will be authorized according to the default policy.
            options.FallbackPolicy = options.DefaultPolicy;
        });

in both my front end and back end Program.cs files and

 "windowsAuthentication": true,
 "anonymousAuthentication": false

in both launchSetting.json files.

What am I failing to understand?

1

There are 1 best solutions below

0
pooteeweet On

In case anyone ever experiences the same issue, I solved by by configuring the http client that I was injecting to UseDefaultCreditials:

API's Program.cs

builder.Services.AddHttpClient("API", client => client.BaseAddress = new Uri(baseAddress)).ConfigurePrimaryHttpMessageHandler(() =>  {
     return new HttpClientHandler()
     {
        UseDefaultCredentials = true
     };
 });