1
votes

I'm getting my knickers in a twist trying to understand how to call an API protected via IdentityServer4.

Basically, I have the following sites: - an IdentityServer application, - a web API and - a client web application.

My setup is just like the IdentityServer samples here.

I define a Client which represents my client web application, and an APIResource which represents my Web Api.

From within my client web application I want to make an HTTP call to the WebAPI, but I want to appear as if I am the logged in user, so I want to make the 'email' scope available to the Web Api.

The way I'm doing from within the Web Application is to grab the 'access_token', and to pass it to the Web API:

var accessToken = await httpContextAccessor.HttpContext.Authentication.GetTokenAsync($"access_token");
            var client = new HttpClient();
            client.SetBearerToken(accessToken);

This allows me to call the Client, so the authorization step is working, but the User Claims on the Web Api do not have the appropriate scopes.

Am I doing something wrong?

2

2 Answers

1
votes

The access_token can contain claim information in IdentityServer4. The required claims must be specified in the ApiResource definition.

Otherwise, you have to send a JWT id_token along with the request.

  new ApiResource(ApiResourceNames.SomeApiAccess, "Access to some api.", new List<string>(){
                    new IdentityResources.OpenId().Name,
                    new IdentityResources.Profile().Name,
                    new IdentityResources.Email().Name
                }),
0
votes

You can add scopes in your web api like

app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
    Authority = "https://demo.identityserver.io",
    ApiName = "api1",

    AllowedScopes = { "api1.read", "api1.write" }
});

How did you configure your web api? Post the code if it still doesn't work!