我正在为我的ASP.NET编写完全定制的WebAPi标识。
我以这样的方式重写了我自己派生的OAuthAuthorizationServerProvider:
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
return Task.FromResult<object>(null);
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
// Check User availability ...
//ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
// if i couldn't found user in my DataBase ...
//if (user == null)
//{
//context.SetError("invalid_grant", "The user name or password is incorrect.");
// return;
//}
context.Validated();
}
}GrantResourceOwnerCredentials只是为每个调用返回一个invalid_grant错误。我想处理这件事,但我不知道怎么处理。
发布于 2018-05-05 09:32:41
ValidateClientAuthentication是您进行身份验证检查的地方,如果有任何不匹配的地方,就在这里抛出错误。
将代码移到那里,并在调用context.Validated()之前进行检查。只有在确保所有内容都被正确验证后,才会调用Validate方法。
下面是我不久前所做的这样一个实现的示例:
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
string clientId;
string clientSecret;
//first try to get the client details from the Authorization Basic header
if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
{
//no details in the Authorization Header so try to find matching post values
context.TryGetFormCredentials(out clientId, out clientSecret);
}
if (string.IsNullOrWhiteSpace(clientId) || string.IsNullOrWhiteSpace(clientSecret))
{
context.SetError("client_not_authorized", "invalid client details");
return Task.FromResult<object>(null);
}
var dataLayer = new RepoManager(new DataLayerDapper()).DataLayer;
var audienceDto = dataLayer.GetAudience(clientId);
if (audienceDto == null || !clientSecret.Equals(audienceDto.Secret))
{
context.SetError("unauthorized_client", "unauthorized client");
return Task.FromResult<object>(null);
}
context.Validated();
return Task.FromResult<object>(null);
}注意检查是如何按顺序进行的,某些错误是通过一些适当的错误引发的。
此代码从授权头中获取客户端id和客户端秘密,但您可以轻松地删除所有这些,并使用您自己的检查和数据库调用来替换它。
重要的是,这是你处理这种事情的地方,也是你设置错误的地方,这样你的客户就知道发生了什么。
GrantResourceOwnerCredentials --一旦对调用进行了正确的身份验证,就可以从这里得到,此时您可以开始创建令牌、添加声明和创建身份验证票证。如果上一种方法无法验证请求,则不会命中此方法。
下面是一个有用的例子:
public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
var identity = new ClaimsIdentity("JWT");
identity.AddClaim(new Claim("clientID", context.ClientId));
var props = new AuthenticationProperties(new Dictionary<string, string>
{
{
"audience", context.ClientId
}
});
var ticket = new AuthenticationTicket(identity, props);
context.Validated(ticket);
return Task.FromResult<object>(null);
}现在,如果您得到一个无效的授予错误,这通常是因为您没有在初始调用中设置grant_type,或者设置了错误的值。
在我的例子中,我不得不设置如下:
"grant_type",“密码”
https://stackoverflow.com/questions/50172551
复制相似问题