title: Web API Bearer tokens - can I use custom tokens?
body: <p>I'm securing a Web API site, and I want to use tokens. But, I'm working with a legacy database, where there is a users table and each user already has a token created for them and stored in the table. </p>
  
  <p>I'm trying to work out if I can use the Identity oAuth bearer token auth bits, but plug it all into my existing database, so that</p>
  
  <ol>
  <li>Granting a token just returns the token for that user from the db</li>
  <li>I can validate the token by looking it up in the db and creating an identity from the user (I am using ASP.NET Identity elsewhere in the site for the MVC side of things)</li>
  </ol>
  
  <p>I can't work out if this is going to be possible, or if I should give up and use a standard HTTP handler approach. Here's my fairly standard code so far, which just issues standard tokens, not the existing ones I want to work with.</p>
  
  <pre><code>OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
  {
      AllowInsecureHttp = true,
      TokenEndpointPath = new PathString("/token"),
      AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
      Provider = new SimpleAuthorizationServerProvider()
  };
  
  // Token Generation
  app.UseOAuthAuthorizationServer(OAuthServerOptions);
  
  var bearerAuth = new OAuthBearerAuthenticationOptions()
  {
      Provider = new OAuthBearerAuthenticationProvider()
  };
  
  app.UseOAuthBearerAuthentication(bearerAuth);
  
  
  public class SimpleAuthorizationServerProvider : 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 manager = new UserManager&lt;User, long&gt;(new UserStore(new UserRepository()));
          var user = await manager.FindAsync(context.UserName, context.Password);
  
          if (user == null)
          {
              context.SetError("invalid_grant", "The user name or password is incorrect.");
          }
          else
          {
              var identity = new ClaimsIdentity(context.Options.AuthenticationType);
              identity.AddClaim(new Claim("name",user.Email));
              context.Validated(identity);
          }
  
  
      }
  }
  </code></pre>