【问题标题】:Web API Bearer tokens - can I use custom tokens?Web API Bearer 令牌 - 我可以使用自定义令牌吗?
【发布时间】:2014-08-15 16:43:44
【问题描述】:

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

我正在尝试确定是否可以使用 Identity oAuth 持有者令牌身份验证位,但将其全部插入我现有的数据库中,以便

  1. 授予令牌只是从数据库中返回该用户的令牌
  2. 我可以通过在 db 中查找令牌并从用户创建身份来验证令牌(我在站点的其他地方使用 ASP.NET Identity 作为 MVC 方面的东西)

我不知道这是否可行,或者我是否应该放弃并使用标准的 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);
        }


    }
}

【问题讨论】:

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


    【解决方案1】:

    回答我自己的问题;)

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

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

    【讨论】:

      猜你喜欢
      • 2014-07-06
      • 2016-03-23
      • 2018-12-16
      • 1970-01-01
      • 2014-09-11
      • 2013-11-30
      • 2014-10-05
      • 1970-01-01
      • 2019-02-18
      相关资源
      最近更新 更多