Owin、GrantResourceOwnerCredentials 发送自定义参数

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

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

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

并且能够在 Web 上接收它 Api

//here you get the context.UserName, context.Password and context.Customer

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

我找到了解决方案

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

下载 运行 个样本