[英]Owin, GrantResourceOwnerCredentials send custom parameters
我有一個Web Api,我在其中使用Owin令牌認證 ,因為您知道默認情況下具有此認證方法
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
//here you get the context.UserName and context.Password
// and validates the user
}
這是JavaScript調用
$.ajax({
type: 'POST',
url: Helper.ApiUrl() + '/token',
data: { grant_type: 'password', username: UserName, password: Password },
success: function (result) {
Helper.TokenKey(result.access_token);
Helper.UserName(result.userName);
},
error: function (result) {
Helper.HandleError(result);
}
});
這是完美的,但是問題是我有一個多客戶數據庫,並且我還必須發送Customer ,所以我需要發送這樣的內容
data: { grant_type: 'password', username: UserName, password: Password, customer: Customer }
並能夠在Web Api中接收它
//here you get the context.UserName, context.Password and context.Customer
我找到了解決方案
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
//here you read all the params
var data = await context.Request.ReadFormAsync();
//here you get the param you want
var param = data.Where(x => x.Key == "CustomParam").Select(x => x.Value).FirstOrDefault();
string customer = "";
if (param != null && param.Length > 0)
{
customer = param[0];
}
}
您在Ajax呼叫中發送的是
data: { grant_type: 'password', username: user, password: pwd, CustomParam: 'MyParam' },
您可以在我的github存儲庫中下載正在運行的示例
在ValidateClientAuthentication中,您可以獲取其他參數並將其添加到上下文中
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
//Here we get the Custom Field sent in /Token
string[] customer = context.Parameters.Where(x => x.Key == "customer").Select(x => x.Value).FirstOrDefault();
if (customer.Length > 0 && customer[0].Trim().Length > 0)
{
context.OwinContext.Set<string>("Customer", customer[0].Trim());
}
// Resource owner password credentials does not provide a client ID.
if (context.ClientId == null)
{
context.Validated();
}
return Task.FromResult<object>(null);
}
然后在所需的方法GrantResourceOwnerCredentials中使用它
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
//Here we use the Custom Field sent in /Token
string customer = context.OwinContext.Get<string>("Customer");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.