title: Authenticating WEB API 2 .net framework 4.x in identity server 4 using OIDC
body: <p>I know there are similar questions out there, but still it's not very clear,
  after reading a bunch of posts related to the subject, this how i "understood" the code should look like, i am still dealing with all the concepts involved in oauth/openid/owin/katana/identityserver etc...</p>
  
  <p>Big picture is: i have an angular application,
  where the user register and log in, no consent is needed, once the user is logged in, the SPA will start comunicating with all the api's in the back and the api's should be able to authenticate against the auth server.</p>
  
  <p>So basically,i need my web api to be able to authenticate in identity server 4, through client credentials grant type, with the issued token by the authentication server. </p>
  
  <p>I got this client(web api 2 .net framework 4.5) defined in identiy server 4:</p>
  
  <pre><code>public static IEnumerable&lt;Client&gt; GetClients()
      {    
        //client credentials client
          return new List&lt;Client&gt;
          {
              new Client
          {  ClientId = "client2",
             AllowedGrantTypes = GrantTypes.ClientCredentials,
  
          ClientSecrets =
          {
              new Secret("secret".Sha256())
          },
             AllowedScopes = { "api2" }
  
          },
  
      }
  </code></pre>
  
  <p>In the .net Api side i have this:</p>
  
  <pre><code>public void ConfigureAuth(IAppBuilder app)
          {
              app.UseCookieAuthentication(new CookieAuthenticationOptions
              {
                  AuthenticationType = 
                  CookieAuthenticationDefaults.AuthenticationType
              });
              app.UseOpenIdConnectAuthentication(new 
              OpenIdConnectAuthenticationOptions
              {
                  ClientId = "client2", 
                  Authority = "http://localhost:5000",
                  RequireHttpsMetadata = false,
                  ResponseType = "id_token",
                  Scope = "api2",
                  SignInAsAuthenticationType = 
                  CookieAuthenticationDefaults.AuthenticationType,
              }
          }); 
  </code></pre>
  
  <p>And the controllers are decorated with the Autorize decorator. 
  These are the versions of the packages im using</p>
  
  <pre><code>id="Microsoft.Owin.Security.OpenIdConnect" version="4.0.0"
  id="Microsoft.Owin.Security.OAuth" version="4.0.0"
  id="Microsoft.Owin.Security" version="4.0.0"
  id="Microsoft.Owin" version="4.0.0"
  </code></pre>
  
  <p>By the moment i am using one of the demo projects from the offical project site(<a href="https://github.com/IdentityServer/IdentityServer4.Samples" rel="nofollow noreferrer">https://github.com/IdentityServer/IdentityServer4.Samples</a>), i added an extra call in the MVC demo app to call my api. </p>
  
  <pre><code>public async Task&lt;IActionResult&gt; CallApiUsingUserAccessToken2()
      {
          var accessToken = await HttpContext.GetTokenAsync("access_token");
          var client = new HttpClient();
          client.SetBearerToken(accessToken);
          var content = await 
          client.GetStringAsync("http://localhost:17307/api
                                 /Organization/GetOrganizationById/2007");
          ViewBag.Json = JArray.Parse(content).ToString();
          return View("Json");
      }
  </code></pre>
  
  <p>According to the working demo, there are two ways to do this, but none have worked to me.</p>
  
  <pre><code>public async Task&lt;IActionResult&gt; CallApiUsingClientCredentials2()
  {
                  var tokenClient = new TokenClient("http://localhost:5000/connect/token", "mvc", "secret");
                  var tokenResponse = await tokenClient.RequestClientCredentialsAsync("api1");
  
                  var client = new HttpClient();
                  client.SetBearerToken(tokenResponse.AccessToken);
                  var content = await client.GetStringAsync("http://localhost:17307/api/Organization/GetOrganizationById/2007");
  
                  ViewBag.Json = JArray.Parse(content).ToString();
                  return View("Json");
  }
  </code></pre>
  
  <p>This is part of the response with the error, i am getting in both scenarios:</p>
  
  <pre><code>&lt;div class="row"&gt;
          &lt;div class="col-sm-6"&gt;
              &lt;div class="alert alert-danger"&gt;
                  Sorry, there was an error
  
                      &lt;strong&gt;
                          &lt;em&gt;
                              : invalid_request
                          &lt;/em&gt;
                      &lt;/strong&gt;
                          &lt;div&gt;Invalid redirect_uri&lt;/div&gt;
              &lt;/div&gt;
  
                  &lt;div class="request-id"&gt;Request Id: 0HLIALF7L4N8J:00000001&lt;/div&gt;
          &lt;/div&gt;
      &lt;/div&gt;
  </code></pre>
  
  <p>What is missing here or what is wrong, is the redirect_uri mandatory, why is not present in the configuration section for the .net core ? </p>
  
  <p>This is how configuration of the api looks like in .net core and works fine.</p>
  
  <pre><code>public void ConfigureServices(IServiceCollection services)
  {    
      services.AddMvcCore()
                  .AddAuthorization()
                  .AddJsonFormatters();
  
              services.AddAuthentication("Bearer")
                  .AddIdentityServerAuthentication(options =&gt;
                  {
                      options.Authority = "http://localhost:5000";
                      options.RequireHttpsMetadata = false;
  
                      options.ApiName = "api1";
                  });
  
  }
  </code></pre>
  
  <p>Thanks in advance.</p>
  
  <p><strong>Update</strong></p>
  
  <p>After some experimenting, i comfirming the issue i am having is in the api validating the access token using owin middleware.</p>
  
  <pre><code>public void ConfigureAuth(IAppBuilder app)
  {
  
      app.UseCookieAuthentication(new CookieAuthenticationOptions
      {
          AuthenticationType = "Cookies",
      });
  
      JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary&lt;string, 
      string&gt; 
      ();
  
      app.UseIdentityServerBearerTokenAuthentication
      (new IdentityServerBearerTokenAuthenticationOptions
      {
          Authority = "http://localhost:5000",
          RequiredScopes = new[] { "api2" },
      });
  }
  </code></pre>
  
  <p>I am using identityserver3.accesstokenvalidation to perform the validation, as it is recomended, but after getting the access token in the client application and pass it to the api request, i am getting a 401 unauthorized error, is this because it is expecting to operate under secure HTTPS ?, i notice for accesstokenvalidation v4 you can set "RequireHttpsMetadata = false" but i dont see this in v3, could be this the reason i am not getting the token validating ?</p>