如何在 ASP.NET MVC 5 中实现自定义身份验证

2024-03-30

我正在开发 ASP.NET MVC 5 应用程序。我有一个现有的数据库,我从中创建了 ADO.NET 实体数据模型。 我在该数据库中有一个表,其中包含“用户名”和“密码”列,我想使用它们在我的 Web 应用程序中实现身份验证和授权;由于客户的要求,我无法创建任何其他数据库、表或列,也无法使用标准身份验证。 我不需要管理注册、更改密码或其他内容:只需使用密码和用户名登录即可。 我怎样才能做到这一点?


是的你可以。身份验证和授权部分独立工作。如果您有自己的身份验证服务,则可以只使用 OWIN 的授权部分。考虑你已经有一个UserManager这验证了username and password。因此,您可以在回发登录操作中编写以下代码:

[HttpPost]
public ActionResult Login(string username, string password)
{
    if (new UserManager().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),

              // optionally you could add roles if any
              new Claim(ClaimTypes.Role, "RoleName"),
              new Claim(ClaimTypes.Role, "AnotherRole"),

          },
          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();
}

你的用户管理器可以是这样的:

class UserManager
{
    public bool IsValid(string username, string password)
    {
         using(var db=new MyDbContext()) // use your DbConext
         {
             // for the sake of simplicity I use plain text passwords
             // in real world hashing and salting techniques must be implemented   
             return db.Users.Any(u=>u.Username==username 
                 && u.Password==password); 
         }
    }
}

最后,您可以通过添加一个来保护您的操作或控制器Authorize属性。

[Authorize]
public ActionResult MySecretAction()
{
    // all authorized users can use this method
    // we have accessed current user principal by calling also
    // HttpContext.User
}

[Authorize(Roles="Admin")]
public ActionResult MySecretAction()
{
    // just Admin users have access to this method
} 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 ASP.NET MVC 5 中实现自定义身份验证 的相关文章

随机推荐