Web API承载令牌 - 我可以使用自定义令牌吗?

时间:2014-06-25 08:02:14

标签: c# authentication asp.net-web-api asp.net-identity owin

我正在保护一个Web API站点,我想使用令牌。但是,我正在使用遗留数据库,其中有一个用户表,每个用户已经为它们创建了一个令牌并存储在表中。

如果我可以使用Identity oAuth bearer token auth位,我会尝试解决这个问题,但是将它全部插入我现有的数据库中,以便

  1. 授予令牌只会从db
  2. 返回该用户的令牌
  3. 我可以通过在数据库中查找并从用户创建身份来验证令牌(我在站点的其他位置使用ASP.NET身份用于MVC方面)
  4. 如果可能的话,我无法解决,或者我是否应该放弃并使用标准的HTTP处理程序方法。到目前为止,这是我相当标准的代码,它只发布标准令牌,而不是我想要使用的现有代码。

    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);
            }
    
    
        }
    }
    

1 个答案:

答案 0 :(得分:6)

回答我自己的问题;)

是的,有可能。它主要要求您整理自定义令牌提供程序并在那里实现您的逻辑。一个很好的例子:

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

相关问题