【问题标题】:ASP.NET Identity - Steps for custom authenticationASP.NET Identity - 自定义身份验证的步骤
【发布时间】:2014-08-02 20:16:57
【问题描述】:

环境:Visual Studio 2013,ASP.NET MVC 5

在我将要处理的基于 MVC5 的新项目中,我需要使用一个自定义数据库,该数据库以自己的方式存储用户名、密码和角色。我正在互联网上搜索自定义身份验证的示例。看起来旧式“会员提供者”类已被新的“身份”机制取代。

但是,事实证明,找到一个好的循序渐进示例是徒劳的。有一些链接(今年发布)讨论了实现自定义 IPrincipalDbContext 类。其他一些链接讨论了实现IUserLoginStoreIUserPasswordStore。其他一些人暗示要实现IUserIUserStore 接口。

也许最后一个选项是需要的。有人可以指导我的步骤或指向任何有简单示例的链接吗?比如:

  1. 基于IUser 实现MyUser
  2. 基于IUserStore 实现MyUserStore
  3. 修改web.config以使用MyUserStore
  4. web.config 中删除DefaultConnection,因为它不是必需的

问候。

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-mvc-4 asp.net-mvc-5


    【解决方案1】:

    首先,停下来。不要再考虑“自定义身份验证”了。您不需要自定义身份验证,您只需要自定义存储身份验证数据。

    ASP.NET Identity 从认证过程中抽象出了认证的存储机制。遵循IxxxStore模式的接口有好几个。如IUserStore、IRoleStore等...

    您可以在此处找到有关此的更多信息,以及各种数据库的自定义实现,您可以将其转换为您自己的需求。

    http://odetocode.com/blogs/scott/archive/2014/01/20/implementing-asp-net-identity.aspx

    例如,这里是一个 RavenDB 实现,它在一个类中使用了所有不同的接口。

    https://github.com/tugberkugurlu/AspNet.Identity.RavenDB/blob/master/src/AspNet.Identity.RavenDB/Stores/RavenUserStore.cs

    但是,所有这些都假设您确实需要以完全不同的方式存储数据。如果您只需要将数据存储在不同的列中,那么它可能就像在 IdentityContext 中覆盖 OnModelCreating 并更改正在使用的列的名称一样简单。

    【讨论】:

      【解决方案2】:

      ad.1.

      public class ApplicationUser :IUser
          {
              public string Id
              {
                  get; 
                  set;
              }
      
              public string UserName
              {
                  get;
                  set;
              }
          }
      

      ad.2.

       public class MyStore : IUserStore<ApplicationUser>, IUserPasswordStore<ApplicationUser>, IUserSecurityStampStore<ApplicationUser>, IUserEmailStore<ApplicationUser>
          {
      ... //implement all interfaces here 
      }
      

      广告。 3. 现在您可以创建您的 applicationUserManagerService(您将需要 IdentityMessageService 和 IDataProtectionProvider):

       var applicationUserManagerService = new ApplicationUserManagerService(new MyStore(), emailService, dataProtectionProvider);
      

      尝试使用 IoC 并注册您的 IUserStore(我就是这样做的 - 链接如下):

      unityContainer.RegisterType<IUserStore<ApplicationUser>, MyStore>();
      

      在这里也检查我的答案(我在那里使用 int 作为 UserId): AspIdentiy ApplicationUserManager is Static, how to extend so it participates in my IoC framework?

      【讨论】:

      • 谢谢。解释清楚。
      猜你喜欢
      • 1970-01-01
      • 2019-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-24
      • 1970-01-01
      • 2013-09-06
      相关资源
      最近更新 更多