我的网站身份验证是集中的,我使用网络服务对用户进行身份验证,但我不会存储用户名和密码。 Web服务返回用户登录后插入本地数据库的有效用户的详细信息。我需要在我的网站上授权有效用户并希望使用ASP.NET身份。我很困惑如何将此方法用于授权用户。我可以在没有任何代码优先认证的情况下使用Identity吗?
答案 0 :(得分:3)
据我所知,您希望将用户凭据发送到远程服务器,如果远程服务器接受,则授权MVC应用程序中的用户。在这种情况下,您不需要用户管理器或用户存储。您只需生成具有适当声明的Identity
对象,并使用生成的Identity
对象登录用户。将这个简单的例子视为线索:
[HttpPost]
public ActionResult Login(string username, string password)
{
if (_remoteServer.IsValid(username, password))
{
var ident = new ClaimsIdentity(
new[]
{
// adding following 2 claim just for supporting default antiforgery provider
new Claim(ClaimTypes.NameIdentifier, username),
new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),
new Claim(ClaimTypes.Name, username),
// you could add extra claims like role or even custom one
new Claim(ClaimTypes.Role, "UserRoleName"),
new Claim("MyCustomClaim", "MyValue"),
},
DefaultAuthenticationTypes.ApplicationCookie);
HttpContext.GetOwinContext().Authentication.SignIn(
new AuthenticationProperties { IsPersistent = false }, ident);
return RedirectToAction("MyAction"); // auth succeed
}
// invalid username or password
ModelState.AddModelError("", "invalid username or password");
return View();
}
现在用户已经过身份验证并注入了Identity的管道。
[Authorize]
public ActionResult Foo()
{
}
// since we injected user roles to Identity we could do this as well
[Authorize(Roles="UserRoleName")]
public ActionResult Foo()
{
// since we injected our authentication mechanism to Identity pipeline
// we have access current user principal by calling also
// HttpContext.User
}