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

Posted

技术标签:

【中文标题】如何在 ASP.NET MVC 5 中实现自定义身份验证【英文标题】:How to implement custom authentication in ASP.NET MVC 5 【发布时间】:2015-10-13 14:09:48 【问题描述】:

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

【问题讨论】:

【参考方案1】:

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

[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
 

【讨论】:

我刚刚更新了我的帖子来回答你的问题。 嘿,我想让您知道您的 github 示例(用于 tokenauth)解决了我的问题,非常感谢!如果可以的话,我会支持你的例子 1000 次 :) 需要 nuget 包: - Microsoft.AspNet.Identity.Core - Microsoft.AspNet.Identity.Owin - Microsoft.Owin - Microsoft.Owin.Host.SystemWeb - Microsoft.Owin.Security - Microsoft.Owin .Security.Cookies - Microsoft.Owin.Security.OAuth - Owin 我希望你有这个问题的悬赏,所以我们可以给你 +1000。请在博客的某个地方发布此内容,以便搜索引擎可以访问此内容。这是如此简单而优雅的解决方案。我花了两天时间阅读有关 OWIN 和 OAuth2 提供的信息,但无法连接电线。 @SamFarajpourGhamari:您能解释一下为什么Login 代码中需要这么长的 const 字符串吗? ... new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string")我检查了代码没有它就可以正常工作!

以上是关于如何在 ASP.NET MVC 5 中实现自定义身份验证的主要内容,如果未能解决你的问题,请参考以下文章

如何在 ASP.NET MVC 中实现自定义主体和身份?

如何在 ASP.NET Core 中实现自定义模型验证?

如何在 WCF 服务中实现自定义身份验证

在 MVC 中实现自定义身份和 IPrincipal

如何在 ASP.NET MVC 5 和 WEB API 2 中实现 oauth2 服务器 [关闭]

ASP.NET MVC 5 中的基本身份验证