簡體   English   中英

Web API承載令牌 - 我可以使用自定義令牌嗎?

[英]Web API Bearer tokens - can I use custom tokens?

我正在保護一個Web API站點,我想使用令牌。 但是,我正在使用遺留數據庫,其中有一個用戶表,每個用戶已經為它們創建了一個令牌並存儲在表中。

我正在努力研究如果我可以使用Identity oAuth bearer token auth位,但將其全部插入我現有的數據庫中,以便

  1. 授予令牌只會從db返回該用戶的令牌
  2. 我可以通過在數據庫中查找並從用戶創建標識來驗證令牌(我在站點的其他位置使用ASP.NET標識用於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);
        }


    }
}

回答我自己的問題;)

對的,這是可能的。 它主要要求您整理自定義令牌提供程序並在那里實現您的邏輯。 一個很好的例子:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM