asp.net - 如何在 .net WebApi2 应用程序中使用 OAuth2 token 请求中的额外参数

标签 asp.net oauth-2.0 asp.net-mvc-5 asp.net-web-api2

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

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

这按预期工作。

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

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

最佳答案

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

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

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

关于asp.net - 如何在 .net WebApi2 应用程序中使用 OAuth2 token 请求中的额外参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21243996/

相关文章:

ios - 使用核心 api 上传 DropBox 文件 https ://api-content. dropbox.com/1/files/<root>/<path>

c# - 为什么会出现 SQL 异常?

c# - 从 Azure FTP 传输到另一个 FTP 站点时出现问题

c# - 返回数据集值给出错误

asp.net - Visual Studio无法在mvc3网站web.config中识别ssl和rewrite标签

java - Java 中 Google OAuth 2 进程中的状态参数

c# - 以编程方式按下网页上的按钮

javascript - 带有 oAuth 重定向的 Electron 自定义协议(protocol)

javascript - knockout.js 与 MVC 5 上的 kendo UI MultiSelect

css - 如何在 _Layout 中引用 .less 文件