调用RequestClientCredentialsTokenAsync时,如何解决“对象引用未设置为对象实例”的问题?

时间:2019-06-11 11:50:06

标签: asp.net-core identityserver4

当我尝试发送请求至:

 var client = new HttpClient();
 var resp = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
            {
                Address = "http://localhost:5000/connect/token",
                ClientId = clientId.AsString(),
                ClientSecret = clientSecret,
                GrantType = grantType,
                Scope = scopes
            });

我正在捕获一个异常:System.NullReferenceException:'对象引用未设置为对象的实例:

crit: IdentityServer4.Hosting.IdentityServerMiddleware[0]
      Unhandled exception: Object reference not set to an instance of an object.
System.NullReferenceException: Object reference not set to an instance of an object.
   at IdentityServer4.Validation.DefaultClientConfigurationValidator.ValidateUriSchemesAsync(ClientConfigurationValidationContext context) in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\src\Validation\Default\DefaultClientConfigurationValidator.cs:line 148
   at IdentityServer4.Validation.DefaultClientConfigurationValidator.ValidateAsync(ClientConfigurationValidationContext context) in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\src\Validation\Default\DefaultClientConfigurationValidator.cs:line 52
   at IdentityServer4.Stores.ValidatingClientStore`1.FindClientByIdAsync(String clientId) in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\src\Stores\ValidatingClientStore.cs:line 61
   at IdentityServer4.Stores.IClientStoreExtensions.FindEnabledClientByIdAsync(IClientStore store, String clientId) in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\src\Extensions\IClientStoreExtensions.cs:line 23
   at IdentityServer4.Validation.ClientSecretValidator.ValidateAsync(HttpContext context) in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\src\Validation\Default\ClientSecretValidator.cs:line 67
   at IdentityServer4.Endpoints.TokenEndpoint.ProcessTokenRequestAsync(HttpContext context) in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\src\Endpoints\TokenEndpoint.cs:line 78
   at IdentityServer4.Endpoints.TokenEndpoint.ProcessAsync(HttpContext context) in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\src\Endpoints\TokenEndpoint.cs:line 70
   at IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService events) in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\src\Hosting\IdentityServerMiddleware.cs:line 54

对错误的描述真的很“不错” ...我正在尝试通过使用resharper从库中调试身份代码。当我进入ValidatingClientStore.cs文件的第58行时,该代码由以下代码表示:

 var context = new ClientConfigurationValidationContext(client)

我遇到了上面提到的错误。它只是将我重定向到

C:\local\identity\server4\IdentityServer4\src\IdentityServer4\src\Validation\Default\DefaultClientConfigurationValidator.cs:line 148 

表示方法签名...仅此而已。我不明白自己在做什么错...我正在尝试覆盖身份组件,并且陷入了该错误。 我的Startup.cs配置:

 public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var scope = Configuration["Authentication:Scope:Name"];

            services.AddCors(options =>
            {
                // this defines a CORS policy called "default"
                options.AddPolicy("default", policy =>
                {
                    policy.WithOrigins("http://localhost:4300")
                        .AllowAnyHeader()
                        .AllowAnyMethod();
                });
            });

            services.AddAuth(options =>
            {
                options.Security = new SecurityOptions
                {
                    RequiredScope = scope,
                    IntrospectionOptions = new OAuth2IntrospectionOptions
                    {
                        Authority = Configuration["Authentication:Settings:Authority"],
                        ClientId = Configuration["Authentication:Settings:ApiName"],
                        ClientSecret = Configuration["Authentication:Settings:ApiSecret"],
                        SaveToken = bool.Parse(Configuration["Authentication:Settings:SaveToken"]),
                        NameClaimType = Configuration["Authentication:Settings:NameClaimType"],
                        RoleClaimType = Configuration["Authentication:Settings:RoleClaimType"]
                    }
                };
            });

            services.Configure<List<ApiResourceOption>>(Configuration.GetSection("ApiResources"));
            services.Configure<List<ClientOption>>(Configuration.GetSection("Clients"));
            services.Configure<IdentityServerAuthenticationOptions>(Configuration.GetSection("Authentication:Settings"));

            //register main stores for identity
            services.AddIdentityCore<ApplicationUser>()
                .AddRoles<ApplicationRole>()
                .AddUserStore<ApplicationUserStore>()
                .AddRoleStore<ApplicationRoleStore>()
                .AddUserManager<ApplicationUserManager>()
                .AddUserValidator<CustomUserValidator<ApplicationUser>>()
                .AddDefaultTokenProviders();


            //register identity server 
            services.AddIdentityServer(c =>
                {
                    c.Caching.ClientStoreExpiration = TimeSpan.FromDays(1);
                    c.Caching.ResourceStoreExpiration = TimeSpan.FromDays(1);
                })
                .AddAspNetIdentity<ApplicationUser>()
                .AddClientStore<ApplicationClientStore>()
                .AddResourceStore<ApplicationResourceStore>()
                .AddProfileService<ProfileService<ApplicationUser>>()
                .AddResourceOwnerValidator<CustomResourceOwnerEmailValidator<ApplicationUser>>()
                .AddDeveloperSigningCredential();


            services.AddScoped<IPasswordHasher<ApplicationUser>, IdentityHasherService<ApplicationUser>>();
            services.AddScoped<IPersistedGrantStore, ApplicationPersistedGrantStore>();

            services.TryAddScoped<IPasswordValidator<ApplicationUser>, PasswordValidator<ApplicationUser>>();
            services.TryAddScoped<IPasswordHasher<ApplicationUser>, PasswordHasher<ApplicationUser>>();
            services.TryAddScoped<ILookupNormalizer, UpperInvariantLookupNormalizer>();
            services.TryAddScoped<IRoleValidator<ApplicationRole>, RoleValidator<ApplicationRole>>();
            services.TryAddScoped<IdentityErrorDescriber>();
            services.TryAddScoped<ISecurityStampValidator, SecurityStampValidator<ApplicationUser>>();
            services.TryAddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, UserClaimsPrincipalFactory<ApplicationUser, ApplicationRole>>();
            services.TryAddScoped<UserManager<ApplicationUser>, UserManager<ApplicationUser>>();
            services.TryAddScoped<SignInManager<ApplicationUser>, SignInManager<ApplicationUser>>();
            services.TryAddScoped<RoleManager<ApplicationRole>, AspNetRoleManager<ApplicationRole>>();


            services.Configure<AuthSettings>(Configuration.GetSection("Authentication:Settings"));

            string connection = Configuration.GetConnectionString("Default");
            services.AddDbContext<IdentityContext>(options =>
                options.UseSqlServer(connection));

            services.AddScoped(typeof(IRepository<>), typeof(Repository<>));

            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)
        {
            app.UseCors("default");
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }


            app.UseIdentityServer();
            app.UseMvc();
        }
    }

resp.Value有一个带有错误描述的html页面: exception

1 个答案:

答案 0 :(得分:0)

根据上面的堆栈跟踪,异常发生在{ "TOTAL_ACTIVATION" : [ { "_id" : true, "total" : 4, "totalActiveCustomer" : 4, "totalNonActiveCustomer" : 0 } ], "TOTAL_CUSTOMERS" : [ { "_id" : true, "total" : 4, "totalCustomer" : 4, "totalNonCustomer" : 0 } ], "TOTAL_CANCELLED" : [ { "_id" : true, "total" : 4, "totalCancelledCustomer" : 4, "totalNonCancelledCustomer" : 0 } ], "MONTHLY_ACTIVATION" : [ { "_id" : { "year" : NumberInt(2018), "month" : NumberInt(10) }, "totalThisMonth" : 1, "totalActiveCustomer" : 1, "totalNonActiveCustomer" : 0 }, { "_id" : { "year" : NumberInt(2018), "month" : NumberInt(9) }, "totalThisMonth" : 1, "totalActiveCustomer" : 1, "totalNonActiveCustomer" : 0 }, { "_id" : { "year" : NumberInt(2018), "month" : NumberInt(8) }, "totalThisMonth" : 2, "totalActiveCustomer" : 2, "totalNonActiveCustomer" : 0 } ], "MONTHLY_CUSTOMER" : [ { "_id" : { "year" : NumberInt(2018), "month" : NumberInt(12) }, "totalThisMonth" : 1, "totalCustomer" : 1, "totalNonCustomer" : 0 }, { "_id" : { "year" : NumberInt(2019), "month" : NumberInt(3) }, "totalThisMonth" : 1, "totalCustomer" : 1, "totalNonCustomer" : 0 }, { "_id" : { "year" : NumberInt(2018), "month" : NumberInt(11) }, "totalThisMonth" : 1, "totalCustomer" : 1, "totalNonCustomer" : 0 }, { "_id" : { "year" : NumberInt(2019), "month" : NumberInt(2) }, "totalThisMonth" : 1, "totalCustomer" : 1, "totalNonCustomer" : 0 } ], "MONTHLY_CANCELLED" : [ { "_id" : { "year" : NumberInt(2019), "month" : NumberInt(1) }, "totalThisMonth" : 1, "totalCancelledCustomer" : 1, "totalNonCancelledCustomer" : 0 }, { "_id" : { "year" : NumberInt(2019), "month" : NumberInt(5) }, "totalThisMonth" : 1, "totalCancelledCustomer" : 1, "totalNonCancelledCustomer" : 0 }, { "_id" : { "year" : NumberInt(2019), "month" : NumberInt(4) }, "totalThisMonth" : 2, "totalCancelledCustomer" : 2, "totalNonCancelledCustomer" : 0 } ] } code中,因此很可能在ValidateUriSchemesAsync()null中存在RedirectUris值客户端配置对象之一。