question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Accessing a resource with a scope returns 401 Unauthorized

See original GitHub issue

Confirm you’ve already contributed to this project or that you sponsor it

  • I confirm I’m a sponsor or a contributor

Version

4.x

Question

I have the following scenario:

  1. An OpenIddict-based server
  2. Resource Api 1
  3. Resource Api 2
  4. Client

Resource Api 2 acts as a middleman between Resource Api 1 and the Client, so the flow should be:

  1. (4) gets an access token using client credentials from (1) to access (3)
  2. (4) connects to (3) with the access token
  3. (3) gets an access token using client credentials from (1) to access (2)
  4. (3) connects to (2)

In my server, I first created 2 scopes:

DisplayName = "ResourceApi1",
Name = "api1",
Resources =
{
	"ResourceApi1"
}

DisplayName = "ResourceApi2",
Name = "api2",
Resources =
{
	"ResourceApi2"
}

I also created 3 applications

ClientId = "Server1",
ClientSecret = "abc",
DisplayName = "Resource Server 1",
Permissions =
{
	Permissions.Endpoints.Introspection
}

ClientId = "Server 2",
ClientSecret = "def",
DisplayName = "Resource Server 2",
Permissions =
{
    Permissions.Endpoints.Introspection,
    Permissions.Endpoints.Token,
    Permissions.GrantTypes.ClientCredentials,
    Permissions.Prefixes.Scope + "api1"
}

ClientId = "client",
ClientSecret = "xyz",
DisplayName = "Client",
Permissions =
{
    Permissions.Endpoints.Token,
    Permissions.GrantTypes.ClientCredentials,
    Permissions.Prefixes.Scope + "api2",
}

I then configured the Resource Server 2 as follows:

//Authentication
services.AddAuthentication(options =>
{
    options.DefaultScheme = OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme;
});
services.AddAuthorization();

//Introspection & client credentials flow
services.AddOpenIddict()
    .AddValidation(options =>
    {
        options.SetIssuer("https://serverurlhere");
        options.AddAudiences(""ResourceApi1"");
        options.UseIntrospection()
            .SetClientId("Server 2")
            .SetClientSecret("def");
        options.UseSystemNetHttp();
        options.UseAspNetCore();
    })
    .AddClient(options =>
    {
        options.AllowClientCredentialsFlow();
        options.UseSystemNetHttp().SetProductInformation(typeof(Program).Assembly);
        options.AddRegistration(new OpenIddictClientRegistration
        {
            Issuer = new Uri("https://serverurlhere"], UriKind.Absolute),
            ClientId = "Server 2",
            ClientSecret = "def"
        });
    });

app.UseAuthentication();
app.UseAuthorization();

And finally the client:

var services = new ServiceCollection();

services.AddOpenIddict()
    .AddClient(options =>
    {
        options.AllowClientCredentialsFlow();
        options.DisableTokenStorage();
        options.UseSystemNetHttp().SetProductInformation(typeof(Program).Assembly);
        options.AddRegistration(new OpenIddictClientRegistration
        {
            Issuer = new Uri("https://serverurlhere", UriKind.Absolute),
            ClientId = "Client",
            ClientSecret = "xyz",            
        });
    });
await using var provider = services.BuildServiceProvider();

async Task<string> GetTokenAsync(IServiceProvider provider)
{
    var service = provider.GetRequiredService<OpenIddictClientService>();

    var result = await service.AuthenticateWithClientCredentialsAsync(new()
    {
        Scopes = new List<string>() { "ResourceApi2" }
    });
    return result.AccessToken;
}

The client does get an access token. But when I use that token to access a protected resource on Resource Api 2 I get a 401 Unauthorized error. If I remove the Audiences from the server validation and from the client, everything works fine.

What am I missing when setting the scope?

Issue Analytics

  • State:closed
  • Created 2 months ago
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
cryo75commented, Jul 18, 2023

That did the trick! It works now!

0reactions
kevinchaletcommented, Jul 18, 2023

The error says the introspection request is rejected because the client_id is not listed as a valid audience for the received token. Try adding Server 2 (the client_id you assigned to the API2 project) to the list of resources attached to the ResourceApi2 scope.

Read more comments on GitHub >

github_iconTop Results From Across the Web

identity server after valid token saying unauthorized 401
401 means that the received token is not valid (wrong audience), do check what the aud claim in the access token is and...
Read more >
Forbidden (403), Unauthorized (401), or What Else?
403 Forbidden is the status code to return when a client has valid credentials but not enough privileges to perform an action on...
Read more >
My resource server returns 401 unauthorized when I add ...
My resource server returns 401 unauthorized when I add token with the correct scope and claims. Hey everyone, I've been reading a lot...
Read more >
Resolve 401 unauthorized errors from API Gateway and ...
Note: API Gateway can return 401 Unauthorized errors for a variety of reasons. The following procedure shows how to troubleshoot 401 errors related...
Read more >
Azure Key Vault REST API Error Codes
401 means that the request is unauthenticated for Key Vault. A request is authenticated if: The key vault knows the identity of the...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found