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

前端之家收集整理的这篇文章主要介绍了asp.net – 如何在.net WebApi2应用程序中使用OAuth2令牌请求中的额外参数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个api特定的项目在一个大的.net MVC 5 web解决方案。我使用开箱即用的WebApi2模板通过api验证用户。使用个人帐户进行身份验证,获取访问令牌所需的请求正文是:
grant_type=password&username={someuser}&password={somepassword}
@H_301_4@这按预期工作。

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

@H_301_4@我的问题是,有没有标准的方法来扩展OWIN OAuth2令牌请求的登录要求,以包括更多的数据?而且,你将如何在.NET WebApi2环境中可靠地做到这一点?

解决方法

由于经常是这样,我在提交问题后立即找到答案… @H_301_4@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);
    }
}
@H_301_4@通过简单地添加

var data = await context.Request.ReadFormAsync();
@H_301_4@在方法中,您可以访问请求正文中的所有已发布的变量,并根据需要使用它们。在我的情况下,我立即在用户的空检查之后执行更严格的安全检查。

@H_301_4@希望这有助于某人!

原文链接:https://www.f2er.com/aspnet/254077.html

猜你在找的asp.Net相关文章