title: Validating Tokens Issued by AspNet.Security.OpenIdConnect.Server (ASP.NET vNext)
body: <p>I am using Visual Studio 2015 Enterprise and ASP.NET vNext Beta8 to build an endpoint that both issues and consumes JWT tokens. I Originally approached this by generating the tokens myself, as described <a href="https://stackoverflow.com/questions/31998052/asp-net-5-oauthbearerauthentication-the-following-authentication-scheme-was-not">here</a>. 
  Later a helpful <a href="https://stackoverflow.com/questions/33140360/getting-an-access-token-in-asp-net-5/33147208">article</a> by @Pinpoint revealed that AspNet.Security.OpenIdConnect.Server (a.k.a. OIDC) can be configured to issue and consume the tokens for me. </p>
  
  <p>So I followed those instructions, stood up an endpoint, and by submitting an x-www-form-urlencoded post from <a href="https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en" rel="nofollow noreferrer">postman</a> I receive back a legit token:</p>
  
  <pre><code>{
    "token_type": "bearer",
    "access_token": "eyJ0eXAiO....",
    "expires_in": "3599"
  }
  </code></pre>
  
  <p>This is great but also where I get stuck. Now, how do I annotate a controller action so that it demands this bearer token? </p>
  
  <p>I thought all I would have to do is decorate my controller method with the 
  [Authorize("Bearer")], add an authentication scheme:</p>
  
  <pre class="lang-cs prettyprint-override"><code>        services.AddAuthorization
          (
              options =&gt; 
              {
                  options.AddPolicy
                  (
                      JwtBearerDefaults.AuthenticationScheme, 
                      builder =&gt; 
                      {
                          builder.
                          AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme).
                          RequireAuthenticatedUser().
                          Build();
                      } 
                  );
              }
          );
  </code></pre>
  
  <p>And then call my controller action with the "Authorization bearer eyJ0eXAiO...." header as I had done in my previous example. Sadly, all this approach seems to do though is generate an exception:</p>
  
  <blockquote>
    <p>An unhandled exception occurred while processing the request.</p>
    
    <p>SocketException: No connection could be made because the target machine actively refused it 127.0.0.1:50000</p>
    
    <p>WebException: Unable to connect to the remote server</p>
    
    <p>HttpRequestException: An error occurred while sending the request.</p>
    
    <p>IOException: IDX10804: Unable to retrieve document from: '<a href="http://localhost:50000/.well-known/openid-configuration" rel="nofollow noreferrer">http://localhost:50000/.well-known/openid-configuration</a>'.
    Microsoft.IdentityModel.Logging.LogHelper.Throw(String message, Type exceptionType, EventLevel logLevel, Exception innerException)</p>
    
    <p>InvalidOperationException: IDX10803: Unable to obtain configuration from: '<a href="http://localhost:50000/.well-known/openid-configuration" rel="nofollow noreferrer">http://localhost:50000/.well-known/openid-configuration</a>'. Inner Exception: 'IDX10804: Unable to retrieve document from: '<a href="http://localhost:50000/.well-known/openid-configuration" rel="nofollow noreferrer">http://localhost:50000/.well-known/openid-configuration</a>'.'.</p>
  </blockquote>
  
  <p><br/>
  Consider the following steps to reproduce (but please don't consider this production worthy code):</p>
  
  <ul>
  <li><p>Apply the ASP.NET Beta8 tooling as described <a href="http://blogs.msdn.com/b/webdev/archive/2015/10/15/announcing-availability-of-asp-net-5-beta8.aspx" rel="nofollow noreferrer">here</a></p></li>
  <li><p>Open Visual Studio Enterprise 2015 and create a new Web API ASP.NET 5 Preview Template project</p></li>
  <li><p>Change project.json</p>
  
  <p>{<br/>
    "webroot": "wwwroot",<br/>
    "version": "1.0.0-*",<br/>
  <br/>
    "dependencies": {<br/>
      "Microsoft.AspNet.IISPlatformHandler": "1.0.0-beta8",<br/>
      "Microsoft.AspNet.Mvc": "6.0.0-beta8",<br/>
      "Microsoft.AspNet.Server.Kestrel": "1.0.0-beta8",<br/>
      "Microsoft.AspNet.Authentication.JwtBearer": "1.0.0-beta8",<br/>
      "AspNet.Security.OpenIdConnect.Server": "1.0.0-beta3",<br/>
      "Microsoft.AspNet.Authentication.OpenIdConnect": "1.0.0-beta8",<br/>
      "Microsoft.Framework.ConfigurationModel.Json": "1.0.0-beta4",<br/>
      "Microsoft.AspNet.Diagnostics": "1.0.0-beta8"<br/>
    },<br/>
  <br/>
    "commands": {<br/>
      "web": "Microsoft.AspNet.Server.Kestrel"<br/>
    },<br/>
  <br/>
    "frameworks": {<br/>
      "dnx451": { }<br/>
    },<br/>
  <br/>
    "exclude": [<br/>
      "wwwroot",<br/>
      "node_modules"<br/>
    ],<br/>
    "publishExclude": [<br/>
      "<strong>.user",<br/>
      "</strong>.vspscc"<br/>
    ]<br/>
  }<br/></p></li>
  <li><p>Change Startup.cs as follows (this is courtesy of @Pinpoint's original article; I have removed comments and added the AddAuthorization snip):</p></li>
  </ul>
  
  <pre class="lang-cs prettyprint-override"><code>public class Startup
  {
      public Startup(IHostingEnvironment env)
      {
      }
  
      public void ConfigureServices(IServiceCollection services)
      {
          services.AddAuthorization
          (
              options =&gt; 
              {
                  options.AddPolicy
                  (
                      JwtBearerDefaults.AuthenticationScheme, 
                      builder =&gt; 
                      {
                          builder.
                          AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme).
                          RequireAuthenticatedUser().
                          Build();
                      } 
                  );
              }
          );
          services.AddAuthentication();
          services.AddCaching();
          services.AddMvc();
          services.AddOptions();
      }
  
      // Configure is called after ConfigureServices is called.
      public void Configure(IApplicationBuilder app, IHostingEnvironment env, IOptions&lt;AppSettings&gt; appSettings)
      {
          app.UseDeveloperExceptionPage();
  
          // Add a new middleware validating access tokens issued by the OIDC server.
          app.UseJwtBearerAuthentication(options =&gt; {
              options.AutomaticAuthentication = true;
              options.Audience = "http://localhost:50000/";
              options.Authority = "http://localhost:50000/";
              options.ConfigurationManager = new ConfigurationManager&lt;OpenIdConnectConfiguration&gt;
              (
                  metadataAddress : options.Authority + ".well-known/openid-configuration",
                  configRetriever : new OpenIdConnectConfigurationRetriever(),
                  docRetriever    : new HttpDocumentRetriever { RequireHttps = false }
              );
          });
  
          // Add a new middleware issuing tokens.
          app.UseOpenIdConnectServer
          (
              configuration =&gt; 
              {
                  configuration.Options.TokenEndpointPath= "/authorization/v1";
                  configuration.Options.AllowInsecureHttp = true;
                  configuration.Provider = new OpenIdConnectServerProvider {
  
                      OnValidateClientAuthentication = context =&gt; 
                      {
                          context.Skipped();
                          return Task.FromResult&lt;object&gt;(null);
                      },
  
                      OnGrantResourceOwnerCredentials = context =&gt; 
                      {
                          var identity = new ClaimsIdentity(OpenIdConnectDefaults.AuthenticationScheme);
                          identity.AddClaim( new Claim(ClaimTypes.NameIdentifier, "todo")  );
                          identity.AddClaim( new Claim("urn:customclaim", "value", "token id_token"));
                          context.Validated(new ClaimsPrincipal(identity));
                          return Task.FromResult&lt;object&gt;(null);
                      }
                  };
              }
          );
  
          app.UseMvc();
      }
  }
  </code></pre>
  
  <ul>
  <li>Change wizarded ValuesController.cs to specify an Authorize attribute:</li>
  </ul>
  
  <pre class="lang-cs prettyprint-override"><code>[Route("api/[controller]")]
  public class ValuesController : Controller
  {
      // GET: api/values
      [Authorize("Bearer")] 
      [HttpGet]
      public IEnumerable&lt;string&gt; Get()
      {
          return new string[] { "value1", "value2" };
      }
  }
  </code></pre>
  
  <ul>
  <li><p>Run the project, and acquire a token using <a href="https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en" rel="nofollow noreferrer">postman</a>. To acquire a token use x-www-form-urlencoded POST with "grant_type" of "password", "username" anything, "password" anything and "resource" the address of the API endpoint. My particular URL for example is <a href="http://localhost:37734/authorization/v1" rel="nofollow noreferrer">http://localhost:37734/authorization/v1</a>.</p></li>
  <li><p>Copy the Base64 encoded token, then use the token to call the wizarded values controller using <a href="https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en" rel="nofollow noreferrer">postman</a>. To use the token make a GET with the headers Content-Type application/json and Authorization bearer eyJ0eXAiO....(your token). My particular URL is <a href="http://localhost:37734/api/values" rel="nofollow noreferrer">http://localhost:37734/api/values</a>.</p></li>
  <li><p>Observe the exception mentioned previously.</p></li>
  </ul>
  
  <p>If the [Authorize("Bearer")] approach I'm trying above is the wrong way to go I would be very appreciative if someone could help me understand best practices for how to ingest the JWT token using OIDC.</p>
  
  <p>Thank you.</p>