【问题标题】:identitysever and AspNetUsersidentitysever 和 AspNetUsers
【发布时间】:2018-10-12 06:37:17
【问题描述】:

我有一个设置,我有

services.AddIdentity<AppUser, AppRole>() 
    .AddEntityFrameworkStores<ApplicationDbContext>() 
    .AddUserManager<userManage>()
    .AddDefaultTokenProviders();

其中使用了AppUser 和AppRole,但它似乎因此而失败。我不断得到

ArgumentNullException:值不能为空。参数名称:System.Security.Claims.Claim..ctor 中声明的类型

之后

Microsoft.AspNetCore.Identity.IdentityUserClaim1.ToClaim()

整个原木在底部

在我介绍 IdentityUser 和 IdentityRole 的扩展之前,一切正常

对于 IDS4 设置,我有:

        services.AddIdentityServer(options => {
                options.UserInteraction.LoginUrl = "/Account/Login";
            })
           .AddSigningCredential(new X509Certificate2(Path.Combine(".", "certs"
                                                                 , "IdentityServer4Auth.pfx")))
           .AddAspNetIdentity<AppUser>()
           .AddConfigurationStore(options => {
                options.ConfigureDbContext = builder =>
                    builder.UseSqlServer(connection_string, sql => sql.MigrationsAssembly(migrations_assembly));
            })
           .AddOperationalStore(options => {
                //options.DefaultSchema = "token";
                options.ConfigureDbContext = builder =>
                    builder.UseSqlServer(connection_string, sql => sql.MigrationsAssembly(migrations_assembly));
            })
           .AddInMemoryApiResources(Config.GetApiResources())
           .AddInMemoryIdentityResources(Config.GetIdentityResources())
           .AddJwtBearerClientAuthentication()
           .AddProfileService<IdentityProfileService>();

工作正常,但从

         services.AddIdentity<ApplicationUser, IdentityRole>(options =>
        {  })
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();
        services.AddDistributedMemoryCache();

到

        services.AddIdentity<AppUser, AppRole>()
           .AddEntityFrameworkStores<ApplicationDbContext>()
           .AddUserManager<userManage>()
           .AddDefaultTokenProviders();

现在就杀了它。我知道它在设置 AppUser、AppRole 和 userManage 时有效,因为它们与我的许多应用程序中使用的设置相同,但一旦与 IDS4 混合,它现在就失败了.当它工作时,我扩展了IdentityUser

public class ApplicationUser : IdentityUser {}

它也可以工作,当我将这两个应用程序混合在一起时,两个应用程序都有AppUser、AppRole 和userManage,这是它变坏的时候。 我会把模型放在下面

旁注也是,我已经按照日志进行了操作,在这里让我感到沮丧的是在数据库中运行的查询是正确的。当我运行它时,我看不到任何类型值的空值。为了安全起见,我什至清理了数据库中任何声明区域中的任何空值,例如角色或用户级别。我已经在导致故障的区域放置了一个断点,

    var signin_result = await _signInManager.PasswordSignInAsync(_user, test, model.RememberMe, false);

当我查看 _user 时,我发现它有安全标记并且所有值都正确填写

它在用户声明中

SELECT [uc].[Id], [uc].[ClaimType], [uc].[ClaimValue], [uc].[UserId]
FROM [AspNetUserClaims] AS [uc]
WHERE [uc].[UserId] = @__user_Id_0

但我看不出问题出在哪里,什么都没有返回一个空值

日志

2018-10-08 13:17:47.164 -07:00 [Information] Entity Framework Core "2.1.4-rtm-31024" initialized '"ApplicationDbContext"' using provider '"Microsoft.EntityFrameworkCore.SqlServer"' with options: "SensitiveDataLoggingEnabled "
2018-10-08 13:17:47.189 -07:00 [Information] Executed DbCommand ("1"ms) [Parameters=["@__user_Id_0='11325643' (Size = 450)"], CommandType='Text', CommandTimeout='30']"
""SELECT [uc].[Id], [uc].[ClaimType], [uc].[ClaimValue], [uc].[UserId]
FROM [AspNetUserClaims] AS [uc]
WHERE [uc].[UserId] = @__user_Id_0"
2018-10-08 13:17:47.370 -07:00 [Error] An exception occurred in the database while iterating the results of a query for context type '"test.app.Data.ApplicationDbContext"'."
""System.ArgumentNullException: Value cannot be null.
Parameter name: type
at System.Security.Claims.Claim..ctor(String type, String value, String valueType, String issuer, String originalIssuer, ClaimsIdentity subject, String propertyKey, String propertyValue)
at System.Security.Claims.Claim..ctor(String type, String value)
at Microsoft.AspNetCore.Identity.IdentityUserClaim`1.ToClaim()
at Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal.ProjectionShaper.TypedProjectionShaper`3.Shape(QueryContext queryContext, ValueBuffer& valueBuffer)
at Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal.ProjectionShaper.TypedProjectionShaper`3.Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal.IShaper<TOut>.Shape(QueryContext queryContext, ValueBuffer& valueBuffer)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1.AsyncEnumerator.BufferlessMoveNext(DbContext _, Boolean buffer, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1.AsyncEnumerator.MoveNext(CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext(CancellationToken cancellationToken)"
System.ArgumentNullException: Value cannot be null.
Parameter name: type
at System.Security.Claims.Claim..ctor(String type, String value, String valueType, String issuer, String originalIssuer, ClaimsIdentity subject, String propertyKey, String propertyValue)
at System.Security.Claims.Claim..ctor(String type, String value)
at Microsoft.AspNetCore.Identity.IdentityUserClaim`1.ToClaim()
at Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal.ProjectionShaper.TypedProjectionShaper`3.Shape(QueryContext queryContext, ValueBuffer& valueBuffer)
at Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal.ProjectionShaper.TypedProjectionShaper`3.Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal.IShaper<TOut>.Shape(QueryContext queryContext, ValueBuffer& valueBuffer)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1.AsyncEnumerator.BufferlessMoveNext(DbContext _, Boolean buffer, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1.AsyncEnumerator.MoveNext(CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext(CancellationToken cancellationToken)
2018-10-08 13:17:48.680 -07:00 [Information] Executed action "WSU.Sso.Controllers.AccountController.Login (test.app)" in 2022.4589ms

模型和设置(注意在无 IDS4 应用程序中这些都可以正常工作)

public class AppUser : IdentityUser {}
public class AppRole : IdentityRole {}
public class AppUserClaim : IdentityUserClaim<string> {}
public class AppUserRole : IdentityUserRole<string> {}
public class AppRoleClaims : IdentityRoleClaim<string> {}
public partial class CoreDbContext : IdentityDbContext
<
    AppUser, // TUser
    AppRole, // TRole
    string, // TKey
    AppUserClaim, // TUserClaim
    AppUserRole, // TUserRole,
    IdentityUserLogin<string>, // TUserLogin
    AppRoleClaims, // TRoleClaim
    IdentityUserToken<string> // TUserToken
>//, ICoreDbContext
{
    //etc.. 
}

更新

我相信问题就在这里,https://github.com/IdentityServer/IdentityServer4.AspNetIdentity/blob/dev/src/UserClaimsFactory.cs 其中UserManager&lt;TUser&gt; userManager 需要是userManage,因为我扩展了它。我猜我似乎需要扮演自己的角色?

更新 2

事实证明,在删除 userManage 扩展 UserManager&lt;TUser&gt; 后,它仍然失败

System.Security.Claims.Claim..ctor(字符串类型,字符串值,字符串 valueType,字符串颁发者,字符串 originalIssuer,ClaimsIdentity 主题,字符串 propertyKey,字符串 propertyValue) System.Security.Claims.Claim..ctor(字符串类型,字符串值) Microsoft.AspNetCore.Identity.IdentityUserClaim.ToClaim()

希望简化它是一个答案,所以我不必重写.AddAspNetIdentity&lt;AppUser&gt;(),但这没有用。很明显,它不是来自数据库的东西是空的,而是必须是添加的东西,它的值是空的。我不知道是什么,只是它必须在Microsoft.AspNetCore.Identity.IdentityUserClaim&lt;TKey&gt;.ToClaim() 和IdentityServer4.AspNetIdentity.UserClaimsFactory&lt;TUser&gt;.CreateAsync(TUser user) in UserClaimsFactory.cs 之间......我可以肯定地说,在https://github.com/IdentityServer/IdentityServer4.AspNetIdentity/blob/dev/src/UserClaimsFactory.cs 中,所有试图设置的部分都经过验证数据库不为空。

在我添加自定义角色之前,IDS4 正在工作也毫无价值。我不是 100% 确定这还没有在这里发挥作用。

旁注

所以我想知道,因为我排除了一些事情,如果这里的问题是 ID 的名称。在更新中,AspNetUser 的表将表设置为user_id 而不是Id(Microsoft Owin Security - Claims Constructor Value cannot be null 是导致我思考这个问题的原因)。话虽如此,我相信设置没有问题,这是我在OnModelCreating(ModelBuilder builder) 中的内容,

builder.Entity<AppUser>().Property(p => p.Id).HasColumnName("user_id");

到目前为止,我们在使用它时没有遇到任何问题,但我正在处理用户中可能成为问题根目录的所有差异。

更新 3

单步执行public class IdentityUserClaim&lt;TKey&gt; where TKey : IEquatable&lt;TKey&gt; 并在Claim ToClaim() 上设置断点后,类型为空。这是日志上的废话,但我似乎无法在调用堆栈中追溯它的根源。我的问题是,如果数据库查询返回一组正确的类型和值,那么为什么要首先处理一个空类型和值?第一次命中断点时,类型为 null。

更新 4 主要停止

在击中每个断点后,如果我在这里遇到错误,我现在会陷入困境。我进入UserManager 并关注堆栈,可以看到主要声明在那里并且正常。

然后下一部分是运行声明存储,它执行上面的查询,此时它失败了。我不明白为什么。我在 SQL 管理器中运行查询,没关系,没有一个 NULL。

有人知道发生了什么吗?我现在不知所措。

更新 5 - 缩小范围

所以当我将声明设置为 null 时没有注意到当地人,我看到我想要的值在 this 的范围内

现在的问题是范围是如何关闭的,我在错误的地方有想要的值

【问题讨论】:

    标签: c# asp.net-core identityserver4 asp.net-core-identity


    【解决方案1】:

    这个问题花了一点时间解决,但现在很清楚为什么会失败。 AppUserClaim 是真正的问题。很难说,在那一步俯瞰当地人,这就是为什么我不得不在这里绕很长一段路。

    我拥有的扩展 IdentityUserClaim&lt;string&gt; 是

    public class AppUserClaim : IdentityUserClaim<string>
    {
        public int Id { get; set; }
    
        /// <summary>
        /// Gets or sets the primary key of the user associated with this claim.
        /// </summary>
        public virtual string UserId { get; set; }
    
        public virtual AppUser user { get; set; }
    
        /// <summary>
        /// Gets or sets the claim type for this claim.
        /// </summary>
        public virtual string ClaimType { get; set; }
    
        /// <summary>
        /// Gets or sets the claim value for this claim.
        /// </summary>
        public virtual string ClaimValue { get; set; }
    
    }
    

    但是ClaimType 和ClaimValue 的属性不需要被覆盖。一旦我这样做了,它就会设置超出方法范围的值。将模型更改为

    public class AppUserClaim : IdentityUserClaim<string>  {
        public virtual AppUser user { get; set; } // note this is the reason why i had to extend
    
    }
    

    解决问题。它没有出现在其他应用程序中,因为声明是从 SSO 设置的,因此总是跳过该方法。

    我要记住的一课,请务必在步入时看着当地人。我花了一天的时间才看到那个糟糕的时刻。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-15
      • 2019-06-05
      • 2015-06-19
      • 2018-08-17
      • 1970-01-01
      • 2020-06-26
      • 2018-07-20
      • 1970-01-01
      相关资源
      最近更新 更多