【问题标题】:InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found. (.net core 5)InvalidOperationException:未指定 authenticationScheme,也未找到 DefaultChallengeScheme。 (.net 核心 5)
【发布时间】:2021-10-11 08:42:36
【问题描述】:

我使用 .net 5 web api 来创建我的应用程序。 我将 [Authorize] 放在我的控制器顶部。 我使用 Identityserver4 作为身份验证服务器。(本地主机:5000) 这是我的 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)
    {

        services.AddControllers();
        services.AddDbContext<MyContext>(opts =>
            opts.UseInMemoryDatabase("MyDb"));

        services.AddAuthentication("bearer")
            .AddIdentityServerAuthentication(opts =>
            {
                opts.Authority = "http://locallhost:5000";
                opts.RequireHttpsMetadata = false;
                opts.ApiName = "myApi";
            });
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "CustomerApi", Version = "v1" });
        });

    }


    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "CustomerApi v1"));
        }

        app.UseAuthentication();
        app.UseRouting();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

但我得到以下错误: error

请指导我解决我的问题。 我搜索了很多时间,但答案是针对 .net 3.1 的。

【问题讨论】:

    标签: asp.net-web-api identityserver4 openapi asp.net-core-5.0


    【解决方案1】:

    我通常有这样的设置:

    app.UseRouting();
    
    app.UseAuthentication();
    app.UseAuthorization();
    
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    
    });
    

    我也不会使用 AddIdentityServerAuthentication(由旧版本的 IdentityServer 使用),而是专注于使用 AddJwtBearer 方法。参见文档here

    【讨论】:

    • 在 app.UseRouting() 之前使用 app.UseAuthorization() 时,它会警告“警告 ASP0001 对 UseAuthorization 的调用应该出现在 app.UseRouting() 和 app.UseEndpoints(..) 之间以进行授权被正确评估。”
    • 是的,我的错误,我发布了一个我通常在我的应用程序中使用的示例管道。
    【解决方案2】:

    您的代码没问题。 但你应该写:

     services.AddAuthentication("Bearer")
    

    而不是

     services.AddAuthentication("bearer")
    

    之后你可能会正确运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-23
      • 2019-11-02
      • 2018-02-26
      • 2021-10-18
      • 2019-03-22
      • 1970-01-01
      • 2019-08-02
      相关资源
      最近更新 更多