【发布时间】:2019-07-05 07:27:05
【问题描述】:
在我的 webAPI 应用程序中,我使用Resource Owner Password Credentials Grant 进行身份验证。当前代码使用用户名和密码可以正常工作。
现在应用程序包含多租户,因此我在用户表中添加了“clientId”详细信息。无论如何,客户端详细信息都在另一个云中,我们可以调用该 api 通过传递 clientId 和密码来验证客户端。
为了实现这一点,我使用ValidateClientAuthentication 方法来验证客户端和GrantResourceOwnerCredentials 方法来验证用户。
这也不错。
问题: 基本上,我还需要支持老客户,所以他们没有客户详细信息。所以如果用户有clientId,我们需要验证客户端,否则只验证用户。
实施:
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
OAuthDefaults.AuthenticationType);
ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(user.UserName,context.ClientId);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
string clientId;
string clientSecret;
context.TryGetFormCredentials(out clientId, out clientSecret);
TenantCloud clientAPI = new TenantCloud();
context.TryGetFormCredentials(out clientId, out clientSecret);
if (clientId != null || clientSecret != null)
{
var tenantResponseJson = await clientAPI.AuthorizeTenant(clientId, clientSecret).ConfigureAwait(false);
if (tenantResponseJson == null || (tenantResponseJson != null && tenantResponseJson.AccessToken == null))
{
context.Rejected();
return;
}
}
context.Validated();
return;
}
如果用户传递客户详细信息,当前代码可以正常工作。但我想确认用户是否有clientid。如果用户有 clientId,它应该验证或返回错误。
要做到这一点,任何从请求中获取用户名的选项,以便我可以获取相应的用户并检查用户是否有 clientId?
【问题讨论】:
标签: oauth-2.0 asp.net-web-api2