Search code examples
asp.net-core-mvcaccess-tokenidentityserver4openid-connect

Getting access_token from identityserver returns null


I have 3 projects, an MVC .net core website, an API service and an IdentityServer (IdentityServer4). Logging in to the website works like a charm. It's when I want to get data from the API the problems are starting. Getting the access_token from the httpcontext fails and returns null. The strange thing is that when I debug this, I seem to be getting an access_token back from the httpcontext. Only when I run the website from the live webserver it causes problems.

I configured my OpenIdConnect as follows:

services.AddAuthentication(options =>
        {

            options.DefaultScheme = "Cookies";
            options.DefaultAuthenticateScheme = "Cookies";
            options.DefaultChallengeScheme = "oidc";
        })
            .AddCookie("Cookies")
            .AddOpenIdConnect("oidc", options =>
            {
                options.SignInScheme = "Cookies";
                options.Authority = "https://idserverurl";
                options.RequireHttpsMetadata = true;
                options.ClientId = "clientid";
                options.ClientSecret = "xxxxxxxx";
                options.ResponseType = "code id_token";

                options.SaveTokens = true;
                options.GetClaimsFromUserInfoEndpoint = true;
                options.Scope.Add("openid");
                options.Scope.Add("profile");
                options.Scope.Add("offline_access");
                };
            });

To set the bearertoken for the API calls I use de following code:

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

When I run this code in debug I get the access_token from the HttpContext. When I run this from the live servers, I get null.

Does anybody have any idea what I'm doing wrong? Could it be a configuration mistake at server level?


Solution

  • I think I solved it myself. It had to do with the line

    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
    

    By removing this line and altering the lines of code where I get my claims (they have a different key now), I am getting the access_token.

    FYI I published the project to my own IIS. That way I could attach Visual Studio to the dotnet process and debug it.

    Why it worked locally and not online I still don't know.