我一直在按照此处找到的教程设置授权服务器,与我的客户端应用程序分开。 http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/
我可以启动并运行他的示例,但我觉得我的应用程序缺少一些步骤。
我想让这个授权服务器提供 oauth token ,一个单独的项目(可能还有多个其他项目)将使用它来对用户进行身份验证。我知道这样做的目的是将授权逻辑和业务逻辑分开,但我不确定如何将 auth 服务器上创建的用户实际配对到应用程序上的用户。
例如,当用户第一次创建帐户时,他们会将用户名/密码发送到授权服务器。该应用程序何时还会创建自己的用户信息(空配置文件和设置等),然后我如何将应用程序的用户 ID 与授权信息一起存储?我已经尝试将客户端 UserID 添加为 auth 服务器上的声明,但我不确定我是否完全理解这意味着什么或者这是否是正确的方法。
基本上,我认为我应该能够做但不确定如何做的是在我的 ASP.Net WebApi 应用程序中,它应该接受 Authorization: Bearer
我的看法是否正确?如何将不同应用程序的 UserID 与在身份验证服务器上创建的用户相关联?
最佳答案
假设我理解您正在尝试正确执行的操作,如果您使用的是 Microsoft 的 OAuth Owin 实现,您应该能够覆盖 OAuthAuthorizationServerProvider,然后覆盖适当的 Grant*()。
参见 http://www.asp.net/aspnet/overview/owin-and-katana/owin-oauth-20-authorization-server了解更多详情。
如果您只是使用 ResourceOwner grant,那非常简单:
public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var user = ...;
if (!PasswordProvider.ValidatePassword(context.Password, user.Password))
{
context.SetError("invalid_grant", "The password is incorrect.");
return Task.FromResult<object>(null);
}
// Build Claims Identity
var identity = new ClaimsIdentity(OwinAuthConfig.OAuthAuthorizationOptions.AuthenticationType);
identity.BuildClaims(user);
// Create the Properties
var properties = CreateProperties(user);
// Create the ticket and process it.
var ticket = new AuthenticationTicket(identity, properties);
context.Validated(ticket);
return Task.FromResult<object>(null);
}
构建声明是这样的:
public static class ApplicationOAuthProviderHelper
{
public static void BuildClaims(this ClaimsIdentity identity, User user)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.Username),
new Claim(ClaimTypes.NameIdentifier, user.UserId.ToString())
};
// Get custom claims, like user app ids.
// ex. Claim { ClaimType = "app1/UserId", Value = "34242" }
var externalAppClaims = MagicalFunctionThatGetsExternalClaims(user);
foreach(var claim in externalAppClaims)
{
claims.Add(new Claim(claim.ClaimType, claim.Value));
}
identity.AddClaims(claims);
}
}
然后可以在 Web API Controller 中用作:
var userIdString = (User.Identity as ClaimsIdentity).FindFirst("app1/UserId");
如果这不能回答您的问题,请告诉我!
关于authentication - OWIN - 将应用程序信息关联到授权服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25366117/