【问题标题】:asp.net core 3 and identityserver4asp.net 核心 3 和 identityserver4
【发布时间】:2020-01-10 07:46:09
【问题描述】:

我按照IdentityServer4 tutorial向使用asp.net core 3 preview 9创建的Web api应用程序添加身份验证。

我的Startup.cs 看起来像这样:

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddAuthorization();
            services.AddAuthentication("Bearer")
                .AddJwtBearer("Bearer", options =>
                {
                    options.Authority = "http://localhost:4800";
                    options.RequireHttpsMetadata = false;

                    options.Audience = "api1";
                });
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

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

我生成了一个有效的 JWT 令牌并将其作为 Bearer 添加到我的请求中,但我总是得到 401 Unauthorized

同一台服务器适用于使用 .net core 2 sdk 创建的 Web api 应用程序。

有什么区别?

【问题讨论】:

  • 您在日志中遇到什么错误?
  • 您应该知道,.net core 3.0 的快速入门尚未更新

标签: c# authentication asp.net-core asp.net-web-api identityserver4


【解决方案1】:

app.UseAuthentication();必须放在app.UseAuthorization()之前;

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        app.UseAuthentication();

        app.UseAuthorization();

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

    }

quickstarts

【讨论】:

    【解决方案2】:
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers()
            .AddNewtonsoftJson();
        services.AddAuthorization();
    
        services.AddAuthentication("Bearer")
          .AddJwtBearer("Bearer", options =>
          {
              options.Authority = "http://localhost:5000";
              options.RequireHttpsMetadata = false;
    
              options.Audience = "api1";
          });
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-15
      • 1970-01-01
      • 2018-10-03
      • 2017-03-12
      • 2018-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多