title: ASP.NET 5 OAuthBearerAuthentication: The following authentication scheme was not accepted: Bearer
body: <h1>Updated:</h1>
  
  <p>Pinpoint helped me get this prototype off the launch pad - I was very close except for:</p>
  
  <ul>
  <li>I need to upgrade to the beta6 SDK as per <a href="https://github.com/aspnet/Announcements/issues/51" rel="nofollow noreferrer">these instructions</a>. Global.json now appears as follows:</li>
  </ul>
  
  <pre class="lang-none prettyprint-override"><code>{
    "projects": [ "src", "test" ],
    "sdk": {
      "version": "1.0.0-beta6"
    }
  }
  </code></pre>
  
  <ul>
  <li>I updated references in project.json:</li>
  </ul>
  
  <pre class="lang-none prettyprint-override"><code>{
    "webroot": "wwwroot",
    "version": "1.0.0-*",
  
    "dependencies": {
      "Microsoft.AspNet.Mvc": "6.0.0-beta6",
      "Microsoft.AspNet.Server.IIS": "1.0.0-beta6",
      "Microsoft.AspNet.Server.WebListener": "1.0.0-beta6",
      "Microsoft.AspNet.StaticFiles": "1.0.0-beta6",
      "System.IdentityModel.Tokens": "5.0.0-beta6-207211625",
      "Serilog.Framework.Logging": "1.0.0-beta-43",
      "Microsoft.AspNet.Authentication.OAuthBearer": "1.0.0-beta6"
    },
  
    "commands": {
      "web": "Microsoft.AspNet.Hosting --config hosting.ini"
    },
  
    "frameworks": {
      "dnx451": { }
    },
  
    "exclude": [
      "wwwroot",
      "node_modules",
      "bower_components"
    ],
    "publishExclude": [
      "node_modules",
      "bower_components",
      "**.xproj",
      "**.user",
      "**.vspscc"
    ]
  }
  </code></pre>
  
  <ul>
  <li>The middleware order in startup's Configure method matters. UseOAuthBearerAuthentication needs to come before UseMvc. The Configure method in Startup.cs now appears as follows:</li>
  </ul>
  
  <pre class="lang-cs prettyprint-override"><code>public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  {
      app.UseOAuthBearerAuthentication();      
  
      app.UseMvc();
  }
  </code></pre>
  
  <hr>
  
  <p>I'm working with ASP.NET 5 and trying to implement an extremely simple proof of concept for generating and consuming JWT tokens. I have read the articles <a href="https://stackoverflow.com/questions/30553991/asp-net-5-jwt-bearer-token-flow">here</a>, <a href="https://stackoverflow.com/questions/31320190/issue-adding-oauth-bearer-authorization-policy-to-asp-net-5-application">here</a> and <a href="https://stackoverflow.com/questions/29055477/oauth-authorization-service-in-asp-net-mvc-6">here</a> but <a href="https://stackoverflow.com/questions/29048122/token-based-authentication-in-asp-net-5-vnext/29698502#29698502">this one</a> most closely matches my needs.</p>
  
  <p>To this end, I very carefully read the article, re-read it, internalized all the comments and then stood up a simple example. I can now generate a JWT token, but when I attempt to call my controller action which has been decorated with an authorize attribute [Authorize("Bearer")], I receive the following message:</p>
  
  <blockquote>
    <p>The following authentication scheme was not accepted: Bearer</p>
  </blockquote>
  
  <p>As I have not seen a high-fidelity A-to-Z example on how to do this, consider the following steps to reproduce:</p>
  
  <ul>
  <li>Create a new Web API Project in Visual Studio 2015 (I am using Enterprise) by selecting "New Project...Web...ASP.NET Web Application" and then the "Web API" option under the "ASP.NET 5 Preview Templates"</li>
  <li>Using the beta 5 SDK, global.json looks like this:</li>
  </ul>
  
  <pre class="lang-none prettyprint-override"><code>{
    "projects": [ "src", "test" ],
    "sdk": {
      "version": "1.0.0-beta5",
      "runtime": "clr",
      "architecture": "x86"
    }
  }
  </code></pre>
  
  <ul>
  <li>Bringing in the dependencies necessary for JWT tokens, project.json looks like this:</li>
  </ul>
  
  <pre class="lang-none prettyprint-override"><code>{
      "webroot": "wwwroot",
      "version": "1.0.0-*",
  
      "dependencies": {
          "Microsoft.AspNet.Mvc": "6.0.0-beta6",
          "Microsoft.AspNet.Server.IIS": "1.0.0-beta6",
          "Microsoft.AspNet.Server.WebListener": "1.0.0-beta6",
          "System.IdentityModel.Tokens": "5.0.0-beta5-206011020",
          "Microsoft.AspNet.Authentication.OAuthBearer": "1.0.0-beta5"
      },
  
      "commands": {
          "web": "Microsoft.AspNet.Hosting --config hosting.ini"
      },
  
      "frameworks": {
          "dnx451": { }
      },
  
      "exclude": [
          "wwwroot",
          "node_modules",
          "bower_components"
      ],
      "publishExclude": [
          "node_modules",
          "bower_components",
          "**.xproj",
          "**.user",
          "**.vspscc"
      ]
  }
  </code></pre>
  
  <ul>
  <li>Startup.cs (this is an <strong>example</strong> not intended for production)</li>
  </ul>
  
  <pre class="lang-cs prettyprint-override"><code>public class Startup
  {
      const string        _TokenIssuer        = "contoso.com"             ;
      const string        _TokenAudience      = "contoso.com/resources"   ;
      RsaSecurityKey      _key                = null                      ;
      SigningCredentials  _signingCredentials = null                      ;
  
      public Startup(IHostingEnvironment env)
      {
          GenerateRsaKeys();
      }
  
      public void ConfigureServices(IServiceCollection services)
      {
          services.AddInstance(_signingCredentials);
  
          services.ConfigureOAuthBearerAuthentication
          (
              options =&gt;
              {
                  options.AutomaticAuthentication = true;
                  options.TokenValidationParameters.IssuerSigningKey  = _key          ;
                  options.TokenValidationParameters.ValidAudience     = _TokenAudience;
                  options.TokenValidationParameters.ValidIssuer       = _TokenIssuer  ;
              }
          );
  
          services.ConfigureAuthorization
          (
              options =&gt;
              {
                  options.
                  AddPolicy
                  (
                      "Bearer",
                      new AuthorizationPolicyBuilder().
                          AddAuthenticationSchemes(OAuthBearerAuthenticationDefaults.AuthenticationScheme).
                          RequireAuthenticatedUser().
                          Build()
                  );
              }
          );
  
          services.AddMvc();
      }
  
      public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILoggerFactory loggerfactory)
      {
          app.UseMvc();
  
          app.UseOAuthBearerAuthentication();
      }
  
      void GenerateRsaKeys()
      {
          using(RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048))
          {
              _key = new RsaSecurityKey(rsa.ExportParameters(true));
  
              _signingCredentials = 
                  new SigningCredentials
                  (
                      _key                                    , 
                      SecurityAlgorithms.RsaSha256Signature   , 
                      SecurityAlgorithms.Sha256Digest         ,
                      "secret"
                  );
  
              rsa.PersistKeyInCsp = false;
          }
      }
  }
  </code></pre>
  
  <ul>
  <li>Some models:</li>
  </ul>
  
  <p>Credentials.cs</p>
  
  <pre class="lang-cs prettyprint-override"><code>public class Credentials
  {
      public string user { set;get;}
      public string password { set;get;}
  }
  </code></pre>
  
  <p>JwtToken.cs</p>
  
  <pre class="lang-cs prettyprint-override"><code>public class JwtToken
  {
      public string access_token  { set; get; }
      public string token_type    { set; get; }
  }
  </code></pre>
  
  <ul>
  <li>A token controller for fetching a token (this is an <strong>example</strong> not intended for production), TokenController.cs:</li>
  </ul>
  
  <pre class="lang-cs prettyprint-override"><code>[ Route("[controller]") ]
  public class TokenController : Controller
  {
      private readonly OAuthBearerAuthenticationOptions   _bearerOptions      ;
      private readonly SigningCredentials                 _signingCredentials ;
  
      public TokenController
      (
          IOptions&lt;OAuthBearerAuthenticationOptions&gt;  bearerOptions       ,
          SigningCredentials                          signingCredentials
      )
      {
          _bearerOptions      = bearerOptions.Options ;
          _signingCredentials = signingCredentials    ;
      }
  
      // POST: /token
      [HttpPost()]
      public JwtToken Token([FromBody] Credentials credentials)
      {
          // Pretend to validate credentials...
  
          JwtSecurityTokenHandler handler = 
              _bearerOptions                      .
              SecurityTokenValidators             .
              OfType&lt;JwtSecurityTokenHandler&gt;()   .
              First();
  
          JwtSecurityToken securityToken = 
              handler     .
              CreateToken
              (
                  issuer              : _bearerOptions.TokenValidationParameters.ValidIssuer  ,
                  audience            : _bearerOptions.TokenValidationParameters.ValidAudience,
                  signingCredentials  : _signingCredentials                                   ,
                  subject             : new ClaimsIdentity
                  (
                      new Claim [] 
                      {
                          new Claim(ClaimTypes.Name,"somebody"),
                          new Claim(ClaimTypes.Role,"admin"   ),
                          new Claim(ClaimTypes.Role,"teacher" ),
                      }
                  ) ,
                  expires             : DateTime.Today.AddDays(1)
              );
  
          string token = handler.WriteToken(securityToken);
  
          return new JwtToken()
          {
              access_token    = token     ,
              token_type      = "bearer"
          };
      }
  }
  </code></pre>
  
  <ul>
  <li>A values controller to demonstrate ingesting the token, ValuesController.cs:</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" };
      }
  
      // GET api/values/5
      [HttpGet("{id}")]
      public string Get(int id)
      {
          return "value";
      }
  }
  </code></pre>
  
  <ul>
  <li>Fire up a copy of <a href="https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en" rel="nofollow noreferrer">postman</a> (or your favorite REST client), launch the sample app under Visual Studio and make a POST request, <strong>similar</strong> to http: // localhost:22553/token/ with the JSON body:</li>
  </ul>
  
  <pre class="lang-none prettyprint-override"><code>{
      "user" : "user",
      "password" : "secret"
  }
  </code></pre>
  
  <p>The app responds with a token:</p>
  
  <pre class="lang-none prettyprint-override"><code>{
    "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6bnVsbH0.eyJ1bmlxdWVfbmFtZSI6InNvbWVib2R5Iiwicm9sZSI6WyJhZG1pbiIsInRlYWNoZXIiXSwiaXNzIjoiY29udG9zby5jb20iLCJhdWQiOiJjb250b3NvLmNvbS9yZXNvdXJjZXMiLCJleHAiOjE0Mzk1MzU2MDB9.anRgL10XFG_bKDDxY3D2xQSfhPRLGMjUTreQNsP1jDA6eRKwXHf3jtpCwm_saoWyUDFFA2TMI9e_LbP6F5l7vtozCluziE_GQkPkspUSWuWIpQJLPRTTPPZHGKmPmK4MLEl1zPPrggJWbvF9RBw3mMQ0KoMfjSL0vUQ8kZ7VXAel8dnYJccd-CFdnB6aDe79x2E9Se2iLxdhr--R_qgvfz1Fa6tR1dstqLQ-UjYqPWY4SOgBjM3abtjfLLVEzeQMVyezX7Cx9ObMXAGbGvQL6GB_T5RlfAoXWME4jM8Bzhd-07wwd732bBws4OXivj1sSz-qawNTnXmnuccLRtI1uA",
    "token_type": "bearer"
  }
  </code></pre>
  
  <ul>
  <li><p>Copy the token from the previous POST, then in postman make a GET request <strong>similar</strong> to http: // localhost:22553/api/values, taking care to add an Authorization header with the value "bearer YOURTOKEN" (e.g. bearer eyJ0eXAiOiJKV1QiLCJ...)</p></li>
  <li><p>Observe that the app responds with the error:</p></li>
  </ul>
  
  <blockquote>
    <p>System.InvalidOperationException
    The following authentication scheme was not accepted: Bearer</p>
  </blockquote>
  
  <p>Stack trace as follows:</p>
  
  <pre class="lang-none prettyprint-override"><code>at Microsoft.AspNet.Http.Authentication.Internal.DefaultAuthenticationManager.&lt; AuthenticateAsync&gt; d__9.MoveNext() 
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.GetResult() 
  at Microsoft.AspNet.Http.Authentication.AuthenticationManager.&lt; AuthenticateAsync&gt; d__2.MoveNext()
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter&lt; TResult&gt; .GetResult() 
  at Microsoft.AspNet.Mvc.AuthorizeFilter.&lt; OnAuthorizationAsync&gt; d__5.MoveNext() 
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.GetResult() 
  at Microsoft.AspNet.Mvc.Core.FilterActionInvoker.&lt; InvokeAuthorizationFilterAsync&gt; d__43.MoveNext()
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.GetResult() 
  at Microsoft.AspNet.Mvc.Core.FilterActionInvoker.&lt; InvokeAllAuthorizationFiltersAsync&gt; d__42.MoveNext() 
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.GetResult() 
  at Microsoft.AspNet.Mvc.Core.FilterActionInvoker.&lt; InvokeAsync&gt; d__40.MoveNext() 
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.GetResult() 
  at Microsoft.AspNet.Mvc.MvcRouteHandler.&lt; InvokeActionAsync&gt; d__4.MoveNext() 
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.GetResult() 
  at Microsoft.AspNet.Mvc.MvcRouteHandler.&lt; RouteAsync&gt; d__3.MoveNext() 
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.GetResult() 
  at Microsoft.AspNet.Mvc.Routing.InnerAttributeRoute.&lt; RouteAsync&gt; d__10.MoveNext() 
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.GetResult() 
  at Microsoft.AspNet.Routing.RouteCollection.&lt; RouteAsync&gt; d__9.MoveNext() 
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.GetResult() 
  at Microsoft.AspNet.Builder.RouterMiddleware.&lt; Invoke&gt; d__4.MoveNext() 
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.GetResult() 
  at Microsoft.AspNet.Hosting.Internal.RequestServicesContainerMiddleware.&lt; Invoke&gt; d__3.MoveNext() 
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.GetResult() 
  at Microsoft.AspNet.Hosting.Internal.HostingEngine.&lt; &gt; c__DisplayClass29_0.&lt; &lt; Start&gt; b__0&gt; d.MoveNext() 
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.GetResult() 
  at Microsoft.AspNet.Loader.IIS.RuntimeHttpApplication.&lt; ProcessRequestAsyncImpl&gt; d__10.MoveNext() 
  --- exception rethrown --- 
  at Microsoft.AspNet.Loader.IIS.RuntimeHttpApplication.&lt; ProcessRequestAsyncImpl&gt; d__10.MoveNext() 
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.GetResult() 
  at Microsoft.AspNet.Loader.IIS.HttpApplicationBase.&lt; InvokeProcessRequestAsyncImpl&gt; d__9.MoveNext()
  </code></pre>
  
  <p>Note that adding logging adds virtually no additional insight, as the following logs show:</p>
  
  <pre class="lang-none prettyprint-override"><code>2015-08-13 13:32:35.969 -07:00 [Information] Request successfully matched the route with name 'null' and template '"api/Values"'.
  Exception thrown: 'System.InvalidOperationException' in Microsoft.AspNet.Http.dll
  2015-08-13 13:32:36.247 -07:00 [Error] An error occurred while handling the request.
  2015-08-13 13:32:36.247 -07:00 System.InvalidOperationException: The following authentication scheme was not accepted: Bearer
  </code></pre>
  
  <p>I am hoping someone might understand where the breakdown in this example is taking place.</p>