ASP.NET MVC身份验证是否与数据库的替代源一起使用?

时间:2017-04-27 21:46:38

标签: asp.net-mvc

我有一个可以查询数据库并返回用户对象的服务。

我想在我的应用程序中使用上述服务实现MVC身份验证。

ASP.NET MVC身份验证是否适用于实体框架工作?如果是,我应该覆盖哪些类实现以使用该服务进行身份验证?

2 个答案:

答案 0 :(得分:1)

要了解的相关组件关系如下:

SignInManagerUserManager进行对话UserStore

要覆盖的类是UserStore。如果从Visual Studio模板创建ASP.NET应用程序,它将提供Microsoft.AspNet.Identity.EntityFramework.UserStore的用户存储。

您可以将此用户商店替换为您自己的MyWcfServiceUserStore(或您选择的任何内容)。

例如,如果您将用户表示为MyUserType,并使用Guid作为唯一标识符:

 public class MyWcfServiceUserStore
    : IUserLockoutStore<MyUserType, Guid>,
      IUserPasswordStore<MyUserType, Guid>,
      IUSerTwoFactorStore<MyUserType, Guid>,
      IUserEmailStore<MyUserType, Guid>
{
   // Lots of methods to implement now
}

然后,您将修改代码,以便UserManager在构造函数中传递MyWcfServiceUserStore

public class ApplicationUserManager : UserManager<MyUserType, Guid>
{
    public ApplicationUserManager(IUserStore<MyUserType, Guid> store)
       : base(store)
    {
    }

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
    {
       var manager = new ApplicationUserManager(new MyWcfServiceUserStore(...));
       //
       // Further initialization here
       //
       return manager;
    }
}

虽然这并非完全无关紧要,但应该直接自己实现所有必需的UserStore方法。需要注意的一点是,在一次网络通话中,UserManager可能会使用相同的查询多次点击UserStore,因此您必须充分利用缓存。

答案 1 :(得分:0)

最简单的黑客是使用表单身份验证,我已经完成了,但没有在生产中。

LoginViewModel

public class LoginViewModel
     {
        [Required]
        public string Username { get; set; }
    [Required]
    [DataType(DataType.Password)]
    public string Password { get; set; }
}

控制器操作

    [HttpPost]
    public ActionResult Login(LoginViewModel login)
    {
        if (!ModelState.IsValid)
        {
            ViewBag.Error = "Form is not valid; please review and try again.";
            return View("Login");
        }

        if ((login.Username == "some@some.com" && login.Password == "NotVeryWise")) { 
            FormsAuthentication.SetAuthCookie(login.Username, false);
            return RedirectToAction("Index", "Home");
        }  


        ViewBag.Error = "Credentials invalid. Please try again.";
        return View("Login");
    }   

的Web.config

    <system.web>
    //...
    //...
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880" defaultUrl="~/Home" />
    </authentication>

  </system.web>

您现在可以在控制器上使用[授权]。