37

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

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

这按预期工作。

但是,我需要向脚手架方法“GrantResourceOwnerCredentials”添加第 3 个维度。除了检查用户名/密码之外,我还需要添加一个设备 ID,这旨在限制从用户帐户对特定设备的访问。不清楚的是如何将这些额外的请求参数添加到已经定义的“OAuthGrantResourceOwnerCredentialsContext”中。此上下文当前为用户名和密码腾出了空间,但显然我需要包含更多内容。

我的问题很简单,是否有一种标准方法可以扩展 OWIN OAuth2 令牌请求的登录要求以包含更多数据?而且,您如何在 .NET WebApi2 环境中可靠地做到这一点?

4

1 回答 1

98

通常情况下,我在提交问题后立即找到了答案...

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

在该方法中,您可以访问请求正文中所有已发布的变量并随意使用它们。在我的例子中,我将它放在对用户进行空检查之后立即执行更严格的安全检查。

希望这对某人有帮助!

于 2014-01-20T21:55:08.137 回答