MVC5中的远端认证和本地授权



我的网站认证是集中的,我用web服务认证我的用户,我不存储用户名和密码。Web服务返回用户登录后插入本地数据库的有效用户的详细信息。我需要授权有效的用户在我的网站,并希望使用ASP。净的身份。我很困惑如何使用这种方法来授权用户。我可以在没有任何代码优先认证的情况下使用Identity吗?

据我所知,您希望将用户凭据发送到远程服务器,如果远程服务器接受它,则在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();
}

现在user被验证并注入到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
} 

相关内容

  • 没有找到相关文章

最新更新