title: Using Claims with OpenIdConnect.Server in ASP.NET 5
body: <p>In the past 7 days I've tried to setup an ASP.NET 5 WebApi using <code>OpenIdConnect.Server</code> with the resource owner flow. </p>
  
  <p>I was more or less successful in generating a token and accessing <code>[Authorize]</code> protected actions. </p>
  
  <p>However, when I try to access <code>this.User.Identity.Claims</code>, it's empty. I am using ASP.NET 5, beta6 for now (having troubles upgrading to most recent beta7 and waiting for it's official release)</p>
  
  <p>In the Startup.cs I got the following:</p>
  
  <pre><code>public void ConfigureServices(IServiceCollection services)
  {
      services.AddCaching();
  
      services.AddEntityFramework()
          .AddSqlServer()
          .AddDbContext&lt;AuthContext&gt;(options =&gt;
          {
              options.UseSqlServer(Configuration.Get("Data:DefaultConnection:ConnectionString"));
          });
  
      services.AddIdentity&lt;AuthUser, AuthRole&gt;(
          options =&gt; options.User = new Microsoft.AspNet.Identity.UserOptions
          {
              RequireUniqueEmail = true,
              UserNameValidationRegex = "^[a-zA-Z0-9@_\\.-]+$"
          })
          .AddEntityFrameworkStores&lt;AuthContext, Guid&gt;()
          .AddDefaultTokenProviders();
  
      services.ConfigureCors(configure =&gt;
      {
          configure.AddPolicy("CorsPolicy", builder =&gt;
          {
              builder.WithOrigins("http:/localhost/", "http://win2012.bludev.com/");
          });
      });
  
      services.AddScoped&lt;IAuthRepository, AuthRepository&gt;();
  }
  
      public void Configure(IApplicationBuilder app)
      {
          var factory = app.ApplicationServices.GetRequiredService&lt;ILoggerFactory&gt;();
          factory.AddConsole();
  
          app.UseStaticFiles();
  
          app.UseOAuthBearerAuthentication(options =&gt;
          {
              options.Authority = "http://win2012.bludev.com/api/auth/";
              options.Audience = "http://win2012.bludev.com/";
  
              options.AutomaticAuthentication = true;
  
              options.TokenValidationParameters = new TokenValidationParameters()
              {
                  RequireExpirationTime = true,
                  RequireSignedTokens = true,
                  RoleClaimType = ClaimTypes.Role,
                  NameClaimType = ClaimTypes.NameIdentifier,
  
                  ValidateActor = true,
                  ValidateAudience = false,
                  ValidateIssuer = true,
                  ValidateLifetime = false,
                  ValidateIssuerSigningKey = true,
                  ValidateSignature = true,
  
                  ValidAudience = "http://win2012.bludev.com/",
                  ValidIssuer = "http://win2012.bludev.com/"
              };
          });
  
          app.UseOpenIdConnectServer(options =&gt;
          {
              options.Issuer = new Uri("http://win2012.bludev.com/api/auth/");
              options.AllowInsecureHttp = true;
              options.AuthorizationEndpointPath = PathString.Empty;
              options.Provider = new AuthorizationProvider();
              options.ApplicationCanDisplayErrors = true;
  
              // Note: in a real world app, you'd probably prefer storing the X.509 certificate
              // in the user or machine store. To keep this sample easy to use, the certificate
              // is extracted from the Certificate.pfx file embedded in this assembly.
              options.UseCertificate(
                  assembly: typeof(Startup).GetTypeInfo().Assembly,
                  resource: "AuthExample.Certificate.pfx",
                  password: "Owin.Security.OpenIdConnect.Server");
          });
  
          app.UseIdentity();
  
          app.UseMvc();
      }
  }
  </code></pre>
  
  <p>I used <code>app.UseOAuthBearerAuthentication</code> because I couldn't get <code>app.UseOpenIdConnectAuthentication</code> working, all I would get is this in the console: </p>
  
  <blockquote>
    <p>request: /admin/user/ warning :
    [Microsoft.AspNet.Authentication.OpenIdConnect.OpenIdConnectAuthentica
    tionMiddleware] OIDCH_0004: OpenIdConnectAuthenticationHandler:
    message.State is  null or empty. request:
    /.well-known/openid-configuration warning :
    [Microsoft.AspNet.Authentication.OpenIdConnect.OpenIdConnectAuthentica
    tionMiddleware] OIDCH_0004: OpenIdConnectAuthenticationHandler:
    message.State is  null or empty.</p>
  </blockquote>
  
  <p>and an Exception after the time out</p>
  
  <blockquote>
    <p>error   : [Microsoft.AspNet.Server.WebListener.MessagePump]
    ProcessRequestAsync System.InvalidOperationException: IDX10803: Unable
    to create to obtain configura tion from:
    '<a href="http://win2012.bludev.com/api/auth/.well-known/openid-configuration" rel="nofollow">http://win2012.bludev.com/api/auth/.well-known/openid-configuration</a>'
    .    at Microsoft.IdentityModel.Logging.LogHelper.Throw(String
    message, Type excep tionType, EventLevel logLevel, Exception
    innerException)    at
    Microsoft.IdentityModel.Protocols.ConfigurationManager`1.d__24.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---    at
    System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
    task)    at
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNot
    ification(Task task)
    ...</p>
  </blockquote>
  
  <p>With this configuration <code>UseOpenIdConnectAuthentication</code></p>
  
  <pre><code>app.UseOpenIdConnectAuthentication(options =&gt;
  {
      options.AuthenticationScheme = OpenIdConnectAuthenticationDefaults.AuthenticationScheme;
  
      options.Authority = "http://win2012.bludev.com/api/auth/";
      options.Audience = "http://win2012.bludev.com/";
      options.Resource = "http://win2012.bludev.com/";
  
      options.AutomaticAuthentication = true;
  
      options.TokenValidationParameters = new TokenValidationParameters()
      {
          RequireExpirationTime = true,
          RequireSignedTokens = true,
          RoleClaimType = ClaimTypes.Role,
          NameClaimType = ClaimTypes.NameIdentifier,
  
          ValidateActor = true,
          ValidateAudience = false,
          ValidateIssuer = true,
          ValidateLifetime = false,
          ValidateIssuerSigningKey = true,
          ValidateSignature = true
      };
  
  });
  </code></pre>
  
  <p>So the real question is: </p>
  
  <ol>
  <li>How to get resource owner flow to work with claims</li>
  <li><code>ValidateLifetime = true</code> or <code>ValidateAudience = true</code> would throw exception and result in a Http Code 500 response without a printed error. </li>
  <li>How to turn authentication failures into a meaningful 400/403 code and a json or xml respones (depending on the client preference) to be displayed for the user? (JavaScript is the client in this case)?</li>
  </ol>