我是.NET的oauth和owin的初学者。我试图了解这些方法的ValidateClientAuthentication方法和GrantResourceOwnerCredentials方法。我了解GrantResourceOwnerCredentials方法可用于验证凭据并生成令牌。然后,方法ValidateClientAuthentication()的目的是什么。请指导我这件事。非常感谢。
public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
return Task.Factory.StartNew(() =>
{
var userName = context.UserName;
var password = context.Password;
var userService = new UserService(); // our created one
var user = userService.ValidateUser(userName, password);
if (user != null)
{
var claims = new List<Claim>()
{
new Claim(ClaimTypes.Sid, Convert.ToString(user.Id)),
new Claim(ClaimTypes.Name, user.Name),
new Claim(ClaimTypes.Email, user.Email)
};
ClaimsIdentity oAuthIdentity = new ClaimsIdentity(claims,Startup.OAuthOptions.AuthenticationType);
var properties = CreateProperties(user.Name);
var ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
}
else
{
context.SetError("invalid_grant", "The user name or password is incorrect");
}
});
}
#endregion
#region[ValidateClientAuthentication]
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
if (context.ClientId == null)
context.Validated();
return Task.FromResult<object>(null);
}
#endregion
这与OAuth 2.0规范中的Client Credentials Flow与Resource Owner Password Credentials Flow有关
请记住,客户端和资源所有者是OAuth下的不同实体。客户端代表资源所有者发出请求。
实际上,当您希望接受实际的用户名和密码并发出访问令牌时,您可能希望使用GrantResourceOwnerCredentials。
应该使用ValidateClientAuthentication来确保客户端是它所说的。如果已将客户端注册到授权服务器并且需要验证它是否仍然有效,那么您可能会这样做。
我见过的大多数代码示例只是调用context.Validated(),就像你在样本中所做的那样。我找到了一篇博客文章,其中包含一个更深入的代码示例。在这里查看:http://bitoftech.net/2014/10/27/json-web-token-asp-net-web-api-2-jwt-owin-authorization-server/