Kris Coleman
Kris Coleman

Reputation: 426

IdentityServer3 - 401 Unauthorized when calling Identity API Controller

I have a project which uses IdentityServer3 for Auth as a Service.

Recently I was tasked with creating a seamless experience for End-Users to edit their identity information.

I did this by creating an API Controller in my application which uses a HTTPClient to call another API Controller living in my IdentityServer project. It basically exposes the Identity management methods to the world, but "passes-through" any requests on to the IdentityServer Api.

All is well right up until I call the IdentityServer Api Controller. My breakpoint there is never hit, regardless of the presence of a "Authorize" attribute. I end up receiving a "401: Unauthorized" back from the IdentityServer Api controller.

I've tried to reuse the original request's Auth headers, but that didn't work. I also tried to find a "access_token" claim from my claim principle, but one wasn't found.

here is a code snippet:

            var httpClient = new HttpClient();

            // this didn't work - tried reusing the auth from the original request
            //httpClient.DefaultRequestHeaders.Authorization = request.Headers.Authorization;

            // this didn't work either - "access_token" is not found 
            //httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", Caller.FindFirst("access_token").Value);
            var routePrefix = GetRoutePrefix();

            var response = await httpClient.PostAsync(
                       $"{routePrefix}/post",
                       new ObjectContent(typeof(TDObj), entity, new JsonMediaTypeFormatter()));

            return response;

I'm new to IdentityServer3 and OAuth and not sure what to do next. I tried creating a new scope for "identity" and tried to make it a required scope in my client application, but that didn't seem to do the trick. I know I'm missing some key piece of understanding here, but there is so much documentation for IdentityServer, I don't know where to begin and can't find anything specific to this need. I'm in the weeds! Can anyone help me understand what's going on here? Thanks!

Upvotes: 0

Views: 2148

Answers (1)

Kris Coleman
Kris Coleman

Reputation: 426

I got it working by following Scott Brady's answer here: Identity Server and web api for user management

However, his answer didn't immediately work for me. I had to make sure to make the call for UseIdentityServerTokenValidation to happen BEFORE api route mapping happened.

That being said, my original attempt to hi-jack the Authorization headers from the inbound HTTPRequest of my Front-End application worked, so I was able to remove any code requesting an access token and didn't have to SetBearerToken() on my HttpClient. Just this:

httpClient.DefaultRequestHeaders.Authorization = request.Headers.Authorization;

Upvotes: 0

Related Questions