Identityserver4 ASP.net标识无效的IdentityServer 4

Identityserver4 ASP.net标识无效的IdentityServer 4,identityserver4,asp.net-core-identity,Identityserver4,Asp.net Core Identity,我正在尝试创建一个身份验证服务器,该服务器具有IdentityServer 4和由Entity Framework支持的ASP.net核心身份 在启动和客户端时,用户和声明存储在ASP.net标识表中,资源存储在identity Server表中 当我试图获取令牌时,我会在屏幕截图中附加错误 Startup.cs public class Startup { // This method gets called by the runtime. Use this meth

我正在尝试创建一个身份验证服务器,该服务器具有IdentityServer 4和由Entity Framework支持的ASP.net核心身份

在启动和客户端时,用户和声明存储在ASP.net标识表中,资源存储在identity Server表中

当我试图获取令牌时,我会在屏幕截图中附加错误

Startup.cs

public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            var connectionString = @"server=localhost;database=IdentityServer;trusted_connection=yes";
            var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            services.AddScoped<ApplicationUser>();

            //services.AddScoped<SignInManager<ApplicationUser>>();

            services.AddScoped<UserManager<ApplicationUser>>();

            services.AddScoped<UserStore<ApplicationUser>>();

            services.AddEntityFrameworkSqlServer();

            services.AddDbContext<ApplicationDbContext>(builder =>
            {
                builder.UseSqlServer(connectionString, options => options.MigrationsAssembly(migrationsAssembly));
            });

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services
                .AddIdentityServer()
                .AddProfileService<ProfileService>()
                .AddResourceOwnerValidator<ResourceOwnerPasswordValidator>()
                .AddTemporarySigningCredential()
                .AddConfigurationStore(builder =>
                    builder.UseSqlServer(connectionString, options =>
                        options.MigrationsAssembly(migrationsAssembly)))
                .AddOperationalStore(builder =>
                    builder.UseSqlServer(connectionString, options =>
                        options.MigrationsAssembly(migrationsAssembly)))
                .AddAspNetIdentity<ApplicationUser>();

            services
                .AddMvcCore()
                .AddJsonFormatters();
        }

        //This method gets called by the runtime.Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            // this will do the initial DB population
            InitializeDatabase(app);

            loggerFactory.AddConsole();

            app.UseIdentity();
            app.UseIdentityServer();

            app.UseStaticFiles();
            app.UseMvcWithDefaultRoute();
        }

        private static void InitializeDatabase(IApplicationBuilder app)
        {
            using (var scope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
            {
                scope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>().Database.Migrate();

                var configContext = scope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
                configContext.Database.Migrate();
                if (!configContext.Clients.Any())
                {
                    foreach (var client in Config.GetClients())
                    {
                        configContext.Clients.Add(client.ToEntity());
                    }
                    configContext.SaveChanges();
                }

                if (!configContext.IdentityResources.Any())
                {
                    foreach (var resource in Config.GetIdentityResources())
                    {
                        configContext.IdentityResources.Add(resource.ToEntity());
                    }
                    configContext.SaveChanges();
                }

                var appContext = app.ApplicationServices.GetRequiredService<ApplicationDbContext>();
                if (!appContext.Users.Any())
                {
                    foreach (var user in Config.GetUsers())
                    {
                        var identityUser = new ApplicationUser();
                        var hash = new PasswordHasher<IdentityUser>().HashPassword(identityUser, user.Password);
                        identityUser.PasswordHash = hash;
                        identityUser.UserName = user.Username;
                        identityUser.NormalizedUserName = user.Username;
                        identityUser.Email = user.Username;
                        identityUser.NormalizedEmail = user.Username;
                        identityUser.EmailConfirmed = true;
                        foreach (var claim in user.Claims)
                        {
                            identityUser.Claims.Add(new IdentityUserClaim<string> { UserId = user.SubjectId, ClaimType = claim.Type, ClaimValue = claim.Value });
                        }
                        appContext.Users.Add(identityUser);
                        appContext.SaveChanges();
                    }
                }

                if (configContext.ApiResources.Any()) return;

                foreach (var resource in Config.GetApiResources())
                {
                    configContext.ApiResources.Add(resource.ToEntity());
                }

                configContext.SaveChanges();
            }
        }
    }
公共类启动
{
//此方法由运行时调用。请使用此方法将服务添加到容器中。
//有关如何配置应用程序的更多信息,请访问https://go.microsoft.com/fwlink/?LinkID=398940
public void配置服务(IServiceCollection服务)
{
services.AddMvc();
var connectionString=@“服务器=localhost;数据库=IdentityServer;可信连接=yes”;
var migrationassembly=typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
services.addScope();
//services.addScope();
services.addScope();
services.addScope();
services.AddEntityFrameworkSqlServer();
services.AddDbContext(builder=>
{
UseSqlServer(connectionString,options=>options.MigrationsAssembly(MigrationsAssembly));
});
服务.额外性()
.AddEntityFrameworkStores()
.AddDefaultTokenProviders();
服务
.AddIdentityServer()
.AddProfileService()
.AddResourceOwnerValidator()
.AddTemporarySigningCredential()
.AddConfigurationStore(生成器=>
builder.UseSqlServer(connectionString,options=>
选项。MigrationAssembly(MigrationAssembly)))
.AddStore(生成器=>
builder.UseSqlServer(connectionString,options=>
选项。MigrationAssembly(MigrationAssembly)))
.addAsNetIdentity();
服务
.AddMvcCore()
.AddJsonFormatters();
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
公共void配置(IApplicationBuilder应用程序、IHostingEnvironment环境、iLogger工厂)
{
//这将完成初始数据库填充
初始化数据库(app);
loggerFactory.AddConsole();
app.UseIdentity();
app.UseIdentityServer();
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
私有静态无效初始化数据库(IApplicationBuilder应用程序)
{
使用(var scope=app.ApplicationServices.GetService().CreateScope())
{
scope.ServiceProvider.GetRequiredService().Database.Migrate();
var configContext=scope.ServiceProvider.GetRequiredService();
configContext.Database.Migrate();
如果(!configContext.Clients.Any())
{
foreach(Config.GetClients()中的var client)
{
configContext.Clients.Add(client.ToEntity());
}
configContext.SaveChanges();
}
如果(!configContext.IdentityResources.Any())
{
foreach(Config.GetIdentityResources()中的var资源)
{
configContext.IdentityResources.Add(resource.ToEntity());
}
configContext.SaveChanges();
}
var appContext=app.ApplicationServices.GetRequiredService();
如果(!appContext.Users.Any())
{
foreach(Config.GetUsers()中的var user)
{
var identityUser=new ApplicationUser();
var hash=new PasswordHasher().HashPassword(identityUser,user.Password);
identityUser.PasswordHash=hash;
identityUser.UserName=user.UserName;
identityUser.NormalizedUserName=user.Username;
identityUser.Email=user.Username;
identityUser.normalizedmail=user.Username;
identityUser.emailconfirm=true;
foreach(user.Claims中的var声明)
{
添加(新的IdentityUserClaim{UserId=user.SubjectId,ClaimType=claim.Type,ClaimValue=claim.Value});
}
appContext.Users.Add(identityUser);
appContext.SaveChanges();
}
}
if(configContext.ApiResources.Any())返回;
foreach(Config.getapirources()中的var资源)
{
configContext.ApiResources.Add(resource.ToEntity());
}
configContext.SaveChanges();
}
}
}
ResourceOwnerPasswordValidator.cs

public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly IUserStore<ApplicationUser> _userStore;

        public ResourceOwnerPasswordValidator(IUserStore<ApplicationUser> userStore, UserManager<ApplicationUser> userManager)
        {
            _userStore = userStore;
            _userManager = userManager;
        }

        public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            var user = await _userStore.FindByNameAsync(context.UserName, CancellationToken.None);
            if (user != null && await _userManager.CheckPasswordAsync(user, context.Password))
            {
                context.Result = new GrantValidationResult(
                    subject: user.Id,
                    authenticationMethod: context.Request.GrantType,
                    claims: user.Claims.Select(c=>new Claim(c.ClaimType, c.ClaimValue)));
            }
            context.Result = new GrantValidationResult(
                TokenRequestErrors.InvalidGrant,
                "invalid custom credential");

        }
    }
公共类ResourceOwnerPasswordValidator:IResourceOwnerPasswordValidator
{
私有只读用户管理器_UserManager;
私有只读IUserStore\u userStore;
公共资源所有者PasswordValidator(IUserStore userStore、UserManager UserManager)
{
_userStore=userStore;
_userManager=userManager;
}
公共异步任务ValidateAsync(ResourceOwnerPasswordValidationContext)
{
var user=await\u userStore.FindByNameAsync(context.UserName,CancellationToken.None);
if(user!=null&&await\u userManager.CheckPasswordAsync(user,context.Password))
{