0
votes

I want to get the claims for an access token, but where I try an get the UserInfo the response returns an error "Forbidden". Why is this and how do I fix it? The userinfo endpoint is https://localhost:44307/connect/userinfo The code below will be refactored once it works. The field response1 contains the error message;

    var client = new HttpClient();
    var disco = await client.GetDiscoveryDocumentAsync(Settings.AuthorityUrl);
    if (disco.IsError)
    {
        throw new Exception(disco.Error);
    }
    var tokenRequest = new ClientCredentialsTokenRequest
    {
        Address = Settings.AuthorityUrl + "connect/token",
        ClientId = Settings.ClientId,
        ClientSecret = "secret",
        Scope = "SIR"
    };

    var response = await client.RequestClientCredentialsTokenAsync(tokenRequest);
    var token = response.AccessToken;
    var response1 = await client.GetUserInfoAsync(new UserInfoRequest
    {
        Address = disco.UserInfoEndpoint,
        Token = token
    });

    if (response1.IsError) throw new Exception(response1.Error);

    var claims = response1.Claims;

In my IDP my config file is

using IdentityServer4;
using IdentityServer4.Models;
using IdentityServer4.Test;
using System.Collections.Generic;
using System.Security.Claims;

namespace QuickstartIdentityServer
{
    public class Config
    {
        // scopes define the resources in your system
        public static IEnumerable<IdentityResource> GetIdentityResources()
        {
            return new List<IdentityResource>
            {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile(),
                new IdentityResources.Address()
            };
        }

        public static IEnumerable<ApiResource> GetApiResources()
        {
            return new List<ApiResource>
            {
                new ApiResource("SIR", "Service Inspection Report")
            };
        }

        // clients want to access resources (aka scopes)
        public static IEnumerable<Client> GetClients()
        {
            var baseUri = "http://localhost:53200/";
            // client credentials client
            return new List<Client>
            {

                // OpenID Connect hybrid flow and client credentials client (MVC)
                new Client
                {
                    ClientId = "SIR",
                    ClientName = "SIR",
                    AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,

                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },

                    RedirectUris = { $"{baseUri}signin-oidc" },
                    PostLogoutRedirectUris = { $"{baseUri}signout-callback-oidc" },

                    AllowedScopes =
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        IdentityServerConstants.StandardScopes.Address,
                        "SIR"
                    },
                    AllowOfflineAccess = true,
                    AlwaysIncludeUserClaimsInIdToken = true
                }
            };
        }

        public static List<TestUser> GetUsers()
        {
            return new List<TestUser>
            {
                new TestUser
                {
                    SubjectId = "1",
                    Username = "alice",
                    Password = "password",

                    Claims = new List<Claim>
                    {
                        new Claim("name", "Alice"),
                        new Claim("website", "https://alice.com"),
                        new Claim("address", "1a The Street")
                    }
                },
                new TestUser
                {
                    SubjectId = "2",
                    Username = "bob",
                    Password = "password",

                    Claims = new List<Claim>
                    {
                        new Claim("name", "Bob"),
                        new Claim("website", "https://bob.com"),
                        new Claim("address", "2a The Street")
                    }
                }
            };
        }
    }
}

And the Startup is;

public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        // configure identity server with in-memory stores, keys, clients and scopes
        services.AddIdentityServer()
            .AddSigningCredential(new X509Certificate2(Settings.CertPath, Settings.Password))
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients())
            .AddTestUsers(Config.GetUsers());

        services.AddAuthentication()
            .AddGoogle("Google", options =>
            {
                options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;

                // register your IdentityServer with Google at https://console.developers.google.com
                // enable the Google+ API
                // set the redirect URI to http://localhost:port/signin-google
                options.ClientId = "copy client ID from Google here";
                options.ClientSecret = "copy client secret from Google here";
            })
            .AddOpenIdConnect("oidc", "OpenID Connect", options =>
            {
                options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
                options.SignOutScheme = IdentityServerConstants.SignoutScheme;

                options.Authority = "https://demo.identityserver.io/";
                options.ClientId = "implicit";

                options.TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = "name",
                    RoleClaimType = "role"
                };
            });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole();
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseMiddleware<StackifyMiddleware.RequestTracerMiddleware>();
        app.UseIdentityServer();
        app.UseStaticFiles();
        app.UseMvcWithDefaultRoute();
    }
}
1
Can you give us some more details about the error?moritzg

1 Answers

3
votes

You are using client credential grant defined by OAuth 2.0.

In your code, RequestClientCredentialsTokenAsync stands for a token request using this grant type. Note that when you obtain an access token through this grant, there is no end user involvement. It is not OpenID Connect (no end user authenticated) and simply works on client credentials, letting you have an access token only.

Now when you use this access token for UserInfo request, identity server detects it to not have any correlated end user. Hence it return forbidden response to let you know that you do not have permission to access the endpoint.

See the exact information from documentation,

The UserInfo endpoint can be used to retrieve identity information about a user (see spec).

The caller needs to send a valid access token representing the user.

If you want user information, use authorization code grant or hybrid flow with scope value openid to enable OpenID Connect request. You can read more here for different grant types.