Web API Bearer tokens - can I use custom tokens?

10,027

Answering my own question ;)

Yes, it is possible. It mostly requires that you sort out a custom Token provider and implement your logic in there. A good sample of this:

https://github.com/eashi/Samples/blob/master/OAuthSample/OAuthSample/App_Start/Startup.Auth.cs

Share:
10,027
Matt Roberts
Author by

Matt Roberts

Updated on June 12, 2022

Comments

  • Matt Roberts
    Matt Roberts almost 2 years

    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.

    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

    1. Granting a token just returns the token for that user from the db
    2. 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)

    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.

    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<User, long>(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);
            }
    
    
        }
    }