问题描述
我在大型 .net MVC 5 Web 解决方案中有一个特定于 api 的项目.我正在使用开箱即用的 WebApi2 模板通过 api 对用户进行身份验证.使用个人账户进行身份验证,获取访问令牌所需的请求正文为:
I have an api specific project in a large .net MVC 5 web solution. I am utilizing the WebApi2 templates out of the box to authenticate a user through the api. Using individual accounts to authenticate, the request body required to get an access token is:
grant_type=password&username={someuser}&password={somepassword}
这按预期工作.
但是,我需要向脚手架方法GrantResourceOwnerCredentials"添加第三个维度.除了检查用户名/密码之外,我还需要添加一个设备 ID,它旨在限制从用户帐户到特定设备的访问.不清楚的是如何将这些额外的请求参数添加到已经定义的OAuthGrantResourceOwnerCredentialsContext"中.这个上下文目前为用户名和密码腾出了空间,但显然我需要包括更多.
However, I need to add a 3rd dimension to the scaffolded method "GrantResourceOwnerCredentials". In addition to checking the username/password, i need to add a device id, which is meant to restrict access from a user account to a specific device. What's not clear is how to add these extra request parameters to the already defined "OAuthGrantResourceOwnerCredentialsContext". This context currently makes room for UserName and Password, but obviously i'll need to include more.
我的问题很简单,是否有一种标准方法可以扩展 OWIN OAuth2 令牌请求的登录要求以包含更多数据?而且,您如何在 .NET WebApi2 环境中可靠地做到这一点?
My question is simply, is there a standard way to extend the login requirements for the OWIN OAuth2 token request to include more data? And, how would you reliably do that in a .NET WebApi2 environment?
推荐答案
因为经常遇到这种情况,我在提交问题后立即找到了答案...
As it often is the case, I found the answer immediately after submitting the question...
ApplicationOAuthProvider.cs 包含以下开箱即用的代码
ApplicationOAuthProvider.cs contains the following code out-of-the-box
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
using (UserManager<IdentityUser> userManager = _userManagerFactory())
{
IdentityUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user,
context.Options.AuthenticationType);
ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(context.UserName, data["udid"]);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
}
只需添加
var data = await context.Request.ReadFormAsync();
在该方法中,您可以访问请求正文中所有已发布的变量并根据需要使用它们.就我而言,我在对用户进行空检查之后立即放置它,以执行更严格的安全检查.
within the method, you can access all posted variables in the request body and use them as you like. In my case, I placed it immediately after the null-check on the user to perform a more restrictive security check.
希望这对某人有所帮助!
Hope this helps someone!
这篇关于您如何在 .net WebApi2 应用程序中使用 OAuth2 令牌请求中的额外参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!