Mat*_*rts 7 c# authentication asp.net-web-api owin asp.net-identity
我正在保护一个Web API站点,我想使用令牌.但是,我正在使用遗留数据库,其中有一个用户表,每个用户已经为它们创建了一个令牌并存储在表中.
我正在努力研究如果我可以使用Identity oAuth bearer token auth位,但是将它全部插入到我现有的数据库中,以便
如果可能的话,我无法解决,或者我是否应该放弃并使用标准的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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
回答我自己的问题;)
对的,这是可能的.它主要要求您整理自定义令牌提供程序并在那里实现您的逻辑.一个很好的例子:
https://github.com/eashi/Samples/blob/master/OAuthSample/OAuthSample/App_Start/Startup.Auth.cs