如何在.NET WebApi2应用程序中使用OAuth2令牌请求中的额外参数

37

我在一个大型的.NET MVC 5 Web解决方案中有一个特定于API的项目。我正在使用WebApi2模板来通过API对用户进行身份验证。使用个人帐户进行身份验证,获取访问令牌所需的请求正文为:

grant_type=password&username={someuser}&password={somepassword}

这个方案符合预期。

然而,我需要在脚手架方法“GrantResourceOwnerCredentials”中添加第三个维度。除了检查用户名/密码之外,我需要添加一个设备ID,以限制用户帐户对特定设备的访问。不清楚的是如何将这些额外的请求参数添加到已定义的“OAuthGrantResourceOwnerCredentialsContext”中。该上下文目前为UserName和Password留有余地,但显然我需要包含更多内容。

我的问题很简单,是否有一种标准方法来扩展OWIN OAuth2令牌请求的登录要求以包括更多数据?并且,在.NET WebApi2环境中,您会如何可靠地实现它?

1个回答

101
通常情况下,就像现在这样,在提交问题后我立即找到了答案... ApplicationOAuthProvider.cs 中包含以下开箱即用的代码。
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();

在该方法中,您可以访问请求体中的所有已发布变量,并根据您的需求使用它们。在我的情况下,我将其放置在对用户进行空值检查之后立即执行更严格的安全性检查。


3
var data = await context.Request.ReadFormAsync(); 真的帮了我很大忙。 - Zapnologica

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接