繁体   English   中英

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

[英]ASP.NET core Web API Authorize Attribute return 404 Error & force redirect

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

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

现在 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();

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

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

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

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

尝试将默认质询设置为返回未授权的 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;
});

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM