我有一个使用 JWT 令牌进行身份验证的 .NET Core 2.2 Web API。令牌由 Identity Server 4 在单独的 API 上生成。所有身份验证和授权都可以使用 JWT 令牌按预期工作。但我需要扩展它以允许使用 API 密钥。如果提供了 API 密钥,我想加载该特定用户的声明,将其添加到请求中并让 Authorize 属性处理设置的策略。这是我按照这里的建议到目前为止所做的。我的错误与链接的帖子完全相同,它也适用于我使用具有一组角色的 GenericPrincipal 但我使用的是 AuthorisationPolicies 并且我当前的实现总是收到 401 错误,给我类似于上面链接的错误。启动.cspublic 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(); }
1 回答

慕无忌1623718
TA贡献1744条经验 获得超4个赞
显然,我必须在此处设置AuthenticationType
为Custom 。ClaimsIdentity
var identity = new ClaimsIdentity(claims, "Custom");
- 1 回答
- 0 关注
- 145 浏览
添加回答
举报
0/150
提交
取消