我假设您可以控制客户端及其发出的请求,以便您可以对身份服务器进行适当的调用。
It is可以使用自定义身份验证逻辑,毕竟这就是ResourceOwnerPassword
流程的全部内容是:客户端将信息传递到 Connect/token 端点,然后您编写代码来决定该信息的含义,并决定这是否足以验证该客户端。不过,您肯定会走出人迹罕至的地方去做您想做的事情,因为按照惯例,客户端传递的信息是username
and a password
.
In your Startup.ConfigureServices
您将需要添加您自己的实现IResourceOwnerPasswordValidator
,有点像这样:
services.AddTransient<IResourceOwnerPasswordValidator, ResourceOwnerPasswordValidator>();
然后在ValidateAsync
该类的方法,您可以执行任何您喜欢的逻辑来决定是否设置context.Result
到一个成功的GrantValidationResult
,或者失败的。用这种方法可以帮助你的一件事是ResourceOwnerPasswordValidationContext
可以访问原始请求。因此,您添加到对连接/令牌端点的原始调用中的任何自定义字段都将可供您使用。您可以在此处添加自定义字段(提供商名称、API 密钥等)。
祝你好运!
编辑:上面的方法可以工作,但实际上是滥用标准拨款/流程。 OP找到的使用方法要好得多IExtensionGrantValidator
用于滚动您自己的授权类型和身份验证逻辑的接口。例如:
从客户端调用身份服务器:
POST /connect/token
grant_type=my_crap_grant&
scope=my_desired_scope&
rhubarb=true&
custard=true&
music=ska
向 DI 注册您的延期补助金:
services.AddTransient<IExtensionGrantValidator, MyCrapGrantValidator>();
并实现您的赠款验证器:
public class MyCrapGrantValidator : IExtensionGrantValidator
{
// your custom grant needs a name, used in the Post to /connect/token
public string GrantType => "my_crap_grant";
public async Task ValidateAsync(ExtensionGrantValidationContext context)
{
// Get the values for the data you expect to be used for your custom grant type
var rhubarb = context.Request.Raw.Get("rhubarb");
var custard = context.Request.Raw.Get("custard");
var music = context.Request.Raw.Get("music");
if (string.IsNullOrWhiteSpace(rhubarb)||string.IsNullOrWhiteSpace(custard)||string.IsNullOrWhiteSpace(music)
{
// this request doesn't have the data we'd expect for our grant type
context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant);
return Task.FromResult(false);
}
// Do your logic to work out, based on the data provided, whether
// this request is valid or not
if (bool.Parse(rhubarb) && bool.Parse(custard) && music=="ska")
{
// This grant gives access to any client that simply makes a
// request with rhubarb and custard both true, and has music
// equal to ska. You should do better and involve databases and
// other technical things
var sub = "ThisIsNotGoodSub";
context.Result = new GrantValidationResult(sub,"my_crap_grant");
Task.FromResult(0);
}
// Otherwise they're unauthorised
context.Result = new GrantValidationResult(TokenRequestErrors.UnauthorizedClient);
return Task.FromResult(false);
}
}