.Net Core 自定义身份验证使用 API 密钥和 Identity Server 4

我有一个使用 JWT 令牌进行身份验证的 .NET Core 2.2 Web API。令牌由 Identity Server 4 在单独的 API 上生成。

所有身份验证和授权都可以使用 JWT 令牌按预期工作。但我需要扩展它以允许使用 API 密钥。如果提供了 API 密钥,我想加载该特定用户的声明,将其添加到请求中并让 Authorize 属性处理设置的策略。

这是我按照这里的建议到目前为止所做的。我的错误与链接的帖子完全相同,它也适用于我使用具有一组角色的 GenericPrincipal 但我使用的是 AuthorisationPolicies 并且我当前的实现总是收到 401 错误,给我类似于上面链接的错误。

启动.cs

public void ConfigureServices(IServiceCollection services)

    {

        services.AddMvcCore(options =>

        {

            options.Filters.Add(new RequireHttpsAttribute());

            options.Filters.Add(new AuthorizeFilter());

            options.Filters.Add(typeof(ValidateModelStateAttribute));

            options.AllowEmptyInputInBodyModelBinding = true;

        })

        .AddAuthorization(options =>

        {

            options.AddPolicies();

        })

        .AddJsonFormatters();


        services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)

            .AddIdentityServerAuthentication(options =>

            {

                options.Authority = Configuration["Authentication:Authority"];

                options.RequireHttpsMetadata = true;

                options.ApiName = Configuration["Authentication:ApiName"];

            });

        services.AddCors();

    }


public void Configure(IApplicationBuilder app, IHostingEnvironment env)

    {

        if (env.IsDevelopment())

        {

            app.UseDeveloperExceptionPage();

        }

        else

        {

            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.

            app.UseHsts();

        }


        app.UseCors(policy =>

        {

            policy.AllowAnyHeader();

            policy.AllowAnyMethod();

            policy.AllowAnyOrigin();

        });


        app.UseHttpsRedirection();

        app.UseMiddleware<ApiKeyMiddleware>();

        app.UseAuthentication();

        app.UseMvc();

    }



茅侃侃
浏览 131回答 1
1回答

慕无忌1623718

显然,我必须在此处设置AuthenticationType为Custom&nbsp;。ClaimsIdentityvar&nbsp;identity&nbsp;=&nbsp;new&nbsp;ClaimsIdentity(claims,&nbsp;"Custom");
打开App,查看更多内容
随时随地看视频慕课网APP