ASP.NET核心Web API授权属性返回404错误&强制重定向

时间:2017-10-10 14:56:17

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

我有asp.net core 2.0解决方案,其中包含以下项目:

  • 数据:EF代码的类库
  • OAuth:作为IdentityServer4代码的Web应用程序项目
  • Api:我的API创建为空的Web项目

现在OAuth项目配置了aspnetidentity并且工作正常,我能够在身份验证后获取令牌,这是它的启动代码:

public void ConfigureServices(IServiceCollection services)
{
    // connect with normal database
    services.AddDbContext<MCareContext>(options => options.UseSqlServer(Configuration
              .GetConnectionString("MCareConnection")));

    services.AddIdentity<User, IdentityRole>()
        .AddEntityFrameworkStores<MCareContext>()
        .AddDefaultTokenProviders();


    services.AddMvc();

    // IS configurations database
    var dbConnectionString = Configuration.GetConnectionString("MCareConnection.OAuth");
    var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

    services.AddIdentityServer()
         .AddConfigurationStore(options =>
         {
            options.ConfigureDbContext = builder =>
                builder.UseSqlServer(dbConnectionString,
                    sql => sql.MigrationsAssembly(migrationsAssembly));
         })

        .AddOperationalStore(options =>
        {
            options.ConfigureDbContext = builder =>
                builder.UseSqlServer(dbConnectionString,
                    sql => sql.MigrationsAssembly(migrationsAssembly));
        })

        .AddAspNetIdentity<User>()
        .AddDeveloperSigningCredential(); 
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    DatabaseInitializer.InitializeDatabase(app);

    loggerFactory.AddConsole();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseIdentityServer();

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

现在关于API项目的问题,每当我打开任何授权的控制器/动作时,它都会给我404错误,这就是启动代码:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<MCareContext>(options => options.UseSqlServer(Configuration
      .GetConnectionString("MCareConnection")));

    services.AddIdentity<User, IdentityRole>()
        .AddEntityFrameworkStores<MCareContext>()
        .AddDefaultTokenProviders();

    services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
     .AddIdentityServerAuthentication(options =>
     {
         options.Authority = "http://localhost:60415";
         options.ApiName = "mCareApi";
         options.RequireHttpsMetadata = false;
     });

    services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole();

    app.UseAuthentication();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseDefaultFiles();
    app.UseStaticFiles();            

    app.UseMvcWithDefaultRoute();
}

如果我在上面的代码中关闭此部分:

//services.AddIdentity<User, IdentityRole>()
    //.AddEntityFrameworkStores<MCareContext>()
    //.AddDefaultTokenProviders();

然后Authorize属性按预期工作,但另一个新问题,它显示500内部服务器错误,每当我打开任何控制器,如AccountController,期望UserManager userManager在其构造函数

  

InvalidOperationException:无法解析类型的服务   Microsoft.AspNetCore.Identity.UserManager`1 [MCare.Data.Entities.User]   在尝试激活MCare.Api.Controllers.AccountsController

我想知道为什么会发生这种情况以及如何解决这个问题,而不将IdentityServer4项目与API项目混合,因为我看到的所有项目都将它们混合在一个项目中。

2 个答案:

答案 0 :(得分:15)

当遇到可能导致404的authorize属性时,DefaultChallengeScheme是否有可能重定向到不存在的页面(例如登录页面)?

尝试将默认质询设置为未经授权的Jwt模式。

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddIdentityServerAuthentication(options =>
{
    options.Authority = "http://localhost:60415";
    options.ApiName = "mCareApi";
    options.RequireHttpsMetadata = false;
});

或者您可以通过为事件提供处理程序来尝试我在下文中提到的方法。

services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
    options.JwtBearerEvents = new JwtBearerEvents
    {
        OnChallenge = context =>
        {
            context.Response.StatusCode = 401;
            return Task.CompletedTask;
        }
    };
    options.Authority = "http://localhost:60415";
    options.ApiName = "mCareApi";
    options.RequireHttpsMetadata = false;
});

答案 1 :(得分:1)

也许您必须在AddControllers()行之后添加AddAuthentication行