Owin,GrantResourceOwnerCredentials发送自定义参数

时间:2018-03-20 21:21:07

标签: javascript c# asp.net-mvc asp.net-web-api owin

我有一个使用 Owin令牌身份验证的Web Api,因为您知道默认使用此方法进行身份验证

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);
            }
        });

这很完美,但问题是我有一个多客户数据库,我还要发送客户,所以我需要发送这样的东西

data: { grant_type: 'password', username: UserName, password: Password, customer: Customer }

能够在Web Api

中收到它
//here you get the context.UserName, context.Password and context.Customer

2 个答案:

答案 0 :(得分:1)

我找到了解决方案

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' },

您可以在my github repository

下载正在运行的示例

答案 1 :(得分:0)

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");
}