1

我正在尝试使用身份 + jwt 授权设置 .net 核心项目,但出现以下错误:

System.InvalidOperationException:无法解析“OpenIddict.Core.IOpenIddictApplicationStore 1[OpenIddict.Models.OpenIddictApplication]' while attempting to activate 'OpenIddict.Core.OpenIddictApplicationManager1 [OpenIddict.Models.OpenIddictApplication]”类型的服务。

这是我的配置:

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();

        services.AddEntityFrameworkSqlServer()
            .AddDbContext<ApplicationDbContext>(options => {
                options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]);
                options.UseOpenIddict();
        });

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

        // add OpenIddict
        services.AddOpenIddict()
            .DisableHttpsRequirement()
            .EnableTokenEndpoint("/api/authenticate/token")
            .AllowPasswordFlow()
            .AllowRefreshTokenFlow()
            .UseJsonWebTokens()
            .AddEphemeralSigningKey();

        services.AddTransient<IDatabaseInitializer, DatabaseInitializer>();
    }

    // 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, IDatabaseInitializer initializer)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions {
                HotModuleReplacement = true
            });
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseOpenIddict();

        // use jwt bearer authentication
        app.UseJwtBearerAuthentication(new JwtBearerOptions
        {
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            RequireHttpsMetadata = false,
            Audience = "http://localhost:1804/",
            Authority = "http://localhost:1804/"
        });

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");

            routes.MapSpaFallbackRoute(
                name: "spa-fallback",
                defaults: new { controller = "Home", action = "Index" });
        });

        initializer.Seed();
    }
}

当我尝试调用/api/authenticate/token路径时出现错误。谁能帮我解决这个问题?

4

1 回答 1

2

哟需要注册实体框架商店。AddEntityFrameworkCoreStores在注册 OpenIddict 服务时添加调用:

 services.AddOpenIddict()
     .AddEntityFrameworkCoreStores<ApplicationDbContext>()
     ...

顺便说一下,考虑使用方法的扩展版本AddOpenIddict(检查 openiddict示例

services.AddOpenIddict(options =>
            {
                 options.DisableHttpsRequirement();

                 options.AllowAuthorizationCodeFlow()
                       .AllowPasswordFlow()
                       .AllowRefreshTokenFlow();
                 ...
            }
于 2017-04-21T09:02:54.227 回答