你可以使用微软的身份对于这种高级场景也是如此。身份如此模块化,您可以将任何数据存储与您想要的任何模式一起使用。 Identity 中的身份验证密码不是必需的,您可以实现自己的场景。考虑这个简单的例子:
// imaging this action is called after user authorized by remote server
public ActionResoult Login()
{
// imaging this method gets authorized certificate string
// from Request.ClientCertificate or even a remote server
var userCer=_certificateManager.GetCertificateString();
// you have own user manager which returns user by certificate string
var user=_myUserManager.GetUserByCertificate(userCer);
if(user!=null)
{
// user is valid, going to authenticate user for my App
var ident = new ClaimsIdentity(
new[]
{
// since userCer is unique for each user we could easily
// use it as a claim. If not use user table ID
new Claim("Certificate", userCer),
// adding following 2 claim just for supporting default antiforgery provider
new Claim(ClaimTypes.NameIdentifier, userCer),
new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),
// an optional claim you could omit this
new Claim(ClaimTypes.Name, user.Name),
// populate assigned user's role form your DB
// and add each one as a claim
new Claim(ClaimTypes.Role, user.Roles[0].Name),
new Claim(ClaimTypes.Role, user.Roles[1].Name),
// and so on
},
DefaultAuthenticationTypes.ApplicationCookie);
// Identity is sign in user based on claim don't matter
// how you generated it Identity take care of it
HttpContext.GetOwinContext().Authentication.SignIn(
new AuthenticationProperties { IsPersistent = false }, ident);
// auth is succeed, without needing any password just claim based
return RedirectToAction("MyAction");
}
// invalid certificate
ModelState.AddModelError("", "We could not authorize you :(");
return View();
}
正如您所看到的,我们授权用户和填充的角色,而不依赖于用户名、密码和任何数据存储,因为我们使用了自己的用户管理器。
一些用法示例:
[Authorize]
public ActionResult Foo()
{
}
// since we injected user roles to Identity we could do this as well
[Authorize(Roles="admin")]
public ActionResult Foo()
{
// since we injected our authentication mechanism to Identity pipeline
// we have access current user principal by calling also
// HttpContext.User
}
这是一个简单的示例,您可以实现自定义场景扩展IIdenity
以及。阅读我的其他类似答案,例如this and this有关更多示例,了解如何通过以下方式完成几乎所有操作Claims
.
您也可以浏览和下载基于令牌的身份验证示例repo 作为一个简单的工作示例。