title: Owin Bearer Token Authentication + Authorize controller
body: <p>I'm trying to do authentication with Bearer tokens and owin. </p>
  
  <p>I can issue the token fine using the grant type <code>password</code> and overriding <code>GrantResourceOwnerCredentials</code> in <strong>AuthorizationServerProvider.cs</strong>.</p>
  
  <p>But I can't reach a controller method with the <code>Authorize</code> attribute.</p>
  
  <p>Here's my code:</p>
  
  <p><strong>Startup.cs</strong></p>
  
  <pre><code>public class Startup
  {
      public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
  
      // normal
      public Startup() : this(false) { }
  
      // testing
      public Startup(bool isDev)
      {
          // add settings
          Settings.Configure(isDev);
  
          OAuthOptions = new OAuthAuthorizationServerOptions
          {
              AllowInsecureHttp = true,
              TokenEndpointPath = new PathString("/Token"),
              AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
              Provider = new AuthorizationServerProvider()
          };
      }
  
      public void Configuration(IAppBuilder app)
      {
          // Configure the db context, user manager and role manager to use a single instance per request
          app.CreatePerOwinContext(ApplicationDbContext.Create);
          app.CreatePerOwinContext&lt;ApplicationUserManager&gt;(ApplicationUserManager.Create);
          app.CreatePerOwinContext&lt;ApplicationRoleManager&gt;(ApplicationRoleManager.Create);
          app.CreatePerOwinContext&lt;ApplicationSignInManager&gt;(ApplicationSignInManager.Create);
          app.CreatePerOwinContext&lt;LoanManager&gt;(BaseManager.Create);
  
          var config = new HttpConfiguration();
          WebApiConfig.Register(config);
          app.UseWebApi(config);
  
          // token generation
          app.UseOAuthAuthorizationServer(OAuthOptions);
          app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
          {
              AuthenticationType = "Bearer",
              AuthenticationMode = AuthenticationMode.Active
          });
      }
  }
  </code></pre>
  
  <p><strong>AuthorizationServerProvider.cs</strong></p>
  
  <pre><code>public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
  {
      public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
      {
          context.Validated();
      }
  
      public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
      {
          context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
          var userManager = context.OwinContext.GetUserManager&lt;ApplicationUserManager&gt;();
  
          IdentityUser user = await userManager.FindAsync(context.UserName, context.Password);
  
          if (user == null)
          {
              context.SetError("invalid_grant", "The user name or password is incorrect.");
              return;
          }
  
          var identity = new ClaimsIdentity(context.Options.AuthenticationType);
          identity.AddClaim(new Claim("sub", context.UserName));
          identity.AddClaim(new Claim("role", "user"));
  
          context.Validated(identity);
      }
  }
  </code></pre>
  
  <p><strong>WebApiConfig.cs</strong></p>
  
  <pre><code>public static class WebApiConfig
  {
      public static void Register(HttpConfiguration config)
      {
          config.MapHttpAttributeRoutes();
  
          // enable CORS for all hosts, headers and methods
          var cors = new EnableCorsAttribute("*", "*", "*");
          config.EnableCors(cors);
  
          config.Routes.MapHttpRoute(
              name: "optional params",
              routeTemplate: "api/{controller}"
          );
  
          config.Routes.MapHttpRoute(
              name: "Default",
              routeTemplate: "api/{controller}/{id}",
              defaults: new { id = RouteParameter.Optional }
          );
  
          // stop cookie auth
          config.SuppressDefaultHostAuthentication();
          // add token bearer auth
          config.Filters.Add(new MyAuthenticationFilter());
          //config.Filters.Add(new HostAuthenticationFilter(Startup.OAuthOptions.AuthenticationType));
  
          config.Filters.Add(new ValidateModelAttribute());
  
          if (Settings.IsDev == false)
          {
              config.Filters.Add(new AuthorizeAttribute());
          }
  
          // make properties on model camelCased
          var jsonFormatter = config.Formatters.OfType&lt;JsonMediaTypeFormatter&gt;().First();
          jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
  
          config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
      }
  </code></pre>
  
  <p><strong>MyAuthenticationFilter.cs</strong> Custom filter used for debugging purposes</p>
  
  <pre><code>public class MyAuthenticationFilter : ActionFilterAttribute, IAuthenticationFilter
  {
      public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
      {
          if (context.Principal != null &amp;&amp; context.Principal.Identity.IsAuthenticated)
          {
          }
  
          return Task.FromResult(0);
      }
  
      public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
      {
          throw new System.NotImplementedException();
      }
  }
  </code></pre>
  
  <p>If I debug <code>AuthenticateAsync</code> in <strong>MyAuthenticationFilter.cs</strong> I see the header in the request:</p>
  
  <pre><code>Authorization: Bearer AQAAANCMnd8BFdERjHoAwE_Cl...
  </code></pre>
  
  <p>But the Identity Claims are empty and <code>context.Principal.Identity.IsAuthenticated</code> is false.</p>
  
  <p>Any ideas?</p>