asp.net-mvc - 使用 Unity 的 MVC5 应用程序中的 ASP.Net Identity 2.1

标签 asp.net-mvc unity-container asp.net-identity

我正在将我的 ASP.Net MVC5 应用程序从 Identity 1 升级到 2.1。 一天后,我让它运行了……但我无法为我的用户验证角色(通过 IsInRole 或授权属性)。 我猜这是因为 MVC 没有解析用户和角色管理器,因为我的应用程序使用 Unity DI,而 Identity 2 似乎基于具有以下配置的 OwinContext:

app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

是否有简单的方法、教程或文档让身份 2 使用外部依赖注入(inject)?

[编辑] 现在 Unity DI 似乎有点工作了(感谢 meep)。

我修改了 Startup.Auth.cs,添加到 ConfigureAuth(IAppBuilder app) 函数:

var container = UnityConfig.Container;
var dbContext = container.Resolve<ApplicationDbContext>();

container.RegisterInstance<IAppBuilder>(app, new ContainerControlledLifetimeManager());
container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>();
container.RegisterType<UserManager<ApplicationUser>, ApplicationUserManager>();
container.RegisterType<IRoleStore<IdentityRole, string>, RoleStore<IdentityRole>>();
container.RegisterType<RoleManager<IdentityRole>, ApplicationRoleManager>();

// [Edit 2]
app.CreatePerOwinContext<ApplicationDbContext>((options, owinContext) => container.Resolve<ApplicationDbContext>());
app.CreatePerOwinContext<UserManager<ApplicationUser>>((options, owinContext) => container.Resolve<UserManager<ApplicationUser>>());
app.CreatePerOwinContext<RoleManager<IdentityRole>>((options, owinContext) => container.Resolve<RoleManager<IdentityRole>>());

在我的 UnitiConfig.cs 文件中,我添加了容器单例的声明(上面使用过)。

在 IdentityConfig.cs 中,我删除了 Create 方法并更改了构造函数

public ApplicationUserManager(IUserStore<ApplicationUser> store, ApplicationDbContext dbContext)
        : base(store)
{
    this.Initialize(dbContext);
}

private void Initialize(ApplicationDbContext dbContext)
{
    // Configurer la logique de validation pour les noms d'utilisateur
    this.UserValidator = new UserValidator<ApplicationUser>(this)
    {
        AllowOnlyAlphanumericUserNames = false,
        RequireUniqueEmail = true
    };
    // ... more code...
}

public class ApplicationRoleManager : RoleManager<IdentityRole>
{
    public ApplicationRoleManager(IRoleStore<IdentityRole, string> roleStore)
        : base(roleStore)
    {
    }
}

我可以对用户进行身份验证...但是 UserManager.GetRoles() 始终为空。 此外 [Authorize(Roles="myrole"] 拒绝每个用户...

最佳答案

好的...谢谢大家! 我明白了!

通过分析发送到 SQL Server 的查询(使用 Express Profiler),我看到 EF 试图在名为 IdentityUser_Id 的列上加入角色表。 回到 SQL Server 中的表定义,我看到了 2 个字段: - 包含 ID 的 UserId - IdentityUser_Id...始终为空! 所以这就是为什么我的角色总是空的!

但是为什么相同的数据有 2 列?

我看了一下EF迁移文件。这里有一些奇怪的线条:

RenameColumn(table: "dbo.T_Securite_AspNetUserClaims", name: "User_Id", newName: "IdentityUser_Id");
AddColumn("dbo.T_Securite_AspNetUserLogins", "IdentityUser_Id", c => c.String(maxLength: 128));
AddColumn("dbo.T_Securite_AspNetUserRoles", "IdentityUser_Id", c => c.String(maxLength: 128));

所以看起来 EF 迁移生成器丢失了。 我更改了 ApplicationDbContext 的 OnModelCreating 方法,通过告知外键的实际位置来帮助它:

modelBuilder.Entity<IdentityUser>()
            .ToTable("T_Security_AspNetUsers"); // Yes... I changed the table name : maybe the source of the problem !

modelBuilder.Entity<IdentityUser>()
            .HasMany(u => u.Roles)
            .WithOptional()
            .HasForeignKey(r => r.UserId);

modelBuilder.Entity<IdentityUser>()
            .HasMany(u => u.Logins)
            .WithOptional()
            .HasForeignKey(l => l.UserId);

modelBuilder.Entity<IdentityUser>()
            .HasMany(u => u.Claims)
            .WithOptional()
            .HasForeignKey(c => c.UserId);

现在 EF 迁移文件看起来更好了。 我为我的用户设置了角色,[Authorize(Role="xxx")] 似乎有效!

关于asp.net-mvc - 使用 Unity 的 MVC5 应用程序中的 ASP.Net Identity 2.1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25785491/

相关文章:

javascript - 无法设置文本区域和复选框以在 mvc5 中设置值

c# - Microsoft Practice 使用 Unity 寄存器类型

c# - 将动态对象映射到接口(interface)并向 IoC 注册

asp.net-mvc - 使用外部访问 token 或本地访问 token

asp.net-mvc - 命名空间未在 VS 代码中的 F# ASP.NET MVC 项目中定义

c# - 如何使用 Advanced Rest Client 发出 POST 请求

asp.net-mvc - MVC 中来自数据库的动态菜单

c# - RegisterType 与 UnityContainer 中的接口(interface)

asp.net-mvc - 更新身份 1 到 2 后,没有 IUserTokenProvider 已注册错误

asp.net-identity - 使用 SQL Server 而不是 LocalDB 的 Web API 和 ASP.Net 标识