【问题标题】:Remote authentication and local authorization in MVC5MVC5 中的远程认证和本地授权
【发布时间】:2015-10-13 09:27:39
【问题描述】:

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

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-identity asp.net-mvc-5.2


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2020-09-06
      • 1970-01-01
      • 2016-05-30
      • 2015-03-05
      • 2018-11-27
      • 2018-07-25
      • 2010-11-14
      • 2021-11-08
      相关资源
      最近更新 更多