我正在开发ASP.NET Web API应用程序。我需要通过登录名和密码对用户进行身份验证,并返回响应字符串令牌。我需要有属性[Authorize]
工作。身份2.0 Web API为客户端生成令牌
我试图调查,如何使用BearerToken机制来做,但没有任何成功。请提供工作代码示例。
我正在开发ASP.NET Web API应用程序。我需要通过登录名和密码对用户进行身份验证,并返回响应字符串令牌。我需要有属性[Authorize]
工作。身份2.0 Web API为客户端生成令牌
我试图调查,如何使用BearerToken机制来做,但没有任何成功。请提供工作代码示例。
您需要配置您的授权服务器(您的情况下是您的授权服务器和资源服务器)以发布访问令牌并使用它们。 这可以使用Owin中间件通过定义和终点来完成,您应该使用grant_type = password将用户凭证(资源所有者流)发送给它。因此,AS将验证这些凭据并为您提供与您配置的过期日期绑定的访问令牌。
public class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureOAuth(app);
//Rest of code is here;
}
public void ConfigureOAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new SimpleAuthorizationServerProvider()
};
// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
// Token Consumption
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
现在,您需要定义一个名为SimpleAuthorizationServerProvider
类和验证的方法凭据GrantResourceOwnerCredentials
如下面的代码:其中你有良好的理解
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[] { "*" });
using (AuthRepository _repo = new AuthRepository())
{
IdentityUser user = await _repo.FindUser(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim("role", "user"));
context.Validated(identity);
}
}
我强烈建议你阅读我的post here您正在安装的组件以及此流程如何工作。
谢谢。这为我节省了很多时间。一些官方的在线文档只是用一种方式使用实体框架工作ORM和代码首先在预定义的表和列的某处创建数据库;生产部署和数据库管理/控制很困难。 – 2016-09-03 19:25:16
请按照this article的说明逐步说明哪些软件包会添加到解决方案中,并在OWIN上提供假OAuth实现。
http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/ – ScottE 2014-09-23 00:14:45