首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在ASP.NET MVC5中实现自定义身份验证

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

Stack Overflow用户
提问于 2015-07-23 18:19:55
回答 1查看 77.7K关注 0票数 80

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-07-23 19:16:21

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

代码语言:javascript
复制
[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();
}

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

代码语言:javascript
复制
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属性来保护您的操作或控制器。

代码语言:javascript
复制
[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
} 
票数 160
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31584506

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档