gpt4 book ai didi

identityserver4 - 如何强制运行身份验证,以便主体可用于其他 ASP.NET Core 中间件?

转载 作者:行者123 更新时间:2023-12-03 21:24:08 25 4
gpt4 key购买 nike

我正在尝试添加一个中间件来根据客户端 ID 在我的 Web API 中实现节流。此 Web API 受 Identity Server 4 和 JWT 身份验证处理程序的保护。

问题是当我的中间件运行时 Context.User.Claims 总是空的。
我知道 Jwt 处理程序仅在请求达到 Authorize 属性时才会被调用。

因此,我的问题是,如何“强制”Jwt 处理程序在管道中更快地运行,以便我的中间件在验证 token 并且 client_id 声明在上下文主体中可用后获得调用?

感谢你给与我的帮助。

设置 Web API 的代码如下:

public void ConfigureServices(IServiceCollection services)
{
// Validation

SmartGuard.NotNull(() => services, services);

// Log

this.Logger.LogTrace("Application services configuration starting.");

// Configuration

services
.AddOptions()
.Configure<ServiceConfiguration>(this.Configuration.GetSection(nameof(ServiceConfiguration)))
.Configure<TelemetryConfiguration>(this.Configuration.GetSection(nameof(TelemetryConfiguration)))
.Configure<TableStorageServiceConfiguration>(this.Configuration.GetSection(nameof(TableStorageServiceConfiguration)))
.UseConfigurationSecrets();

ServiceConfiguration serviceConfiguration = services.ResolveConfiguration<ServiceConfiguration>();

// Telemetry (Application Insights)

services.AddTelemetryForApplicationInsights();

// Memory cache

services.AddDistributedMemoryCache();

// MVC

services.AddMvc();

// Identity

services
.AddAuthorization(
(options) =>
{
options.AddPolicy(
Constants.Policies.Settings,
(policy) =>
{
policy.RequireClaim(Constants.ClaimTypes.Scope, Scopes.Settings);
});
});

// NOTE:
// We are using the JWT Bearer handler here instead of the IdentityServer handler
// because version 2.3.0 does not handle bearer challenges correctly.
// For more info: https://github.com/IdentityServer/IdentityServer4/issues/2047
// This is supposed to be fixed in version 2.4.0.

services
.AddAuthentication(Constants.AuthenticationSchemes.Bearer)
.AddJwtBearer(
(options) =>
{
options.Authority = serviceConfiguration.IdentityServerBaseUri;
options.Audience = Constants.ApiName;
options.RequireHttpsMetadata = false;
options.IncludeErrorDetails = true;
options.RefreshOnIssuerKeyNotFound = true;
options.SaveToken = true;
options.Events = new JwtBearerEvents()
{
OnChallenge = HandleChallenge
};
});

// Web API Versioning

services.AddApiVersioning(
(options) =>
{
options.DefaultApiVersion = new Microsoft.AspNetCore.Mvc.ApiVersion(ApiVersions.DefaultVersion.Major, ApiVersions.DefaultVersion.Minor);
options.ReportApiVersions = true;
options.AssumeDefaultVersionWhenUnspecified = true;
});

// Setup Throttling

services
.AddThrottling()
.AddClientRateHandler(this.Configuration.GetSection(nameof(ClientRateThrottlingOptions)));

// Routes analyzer
// Creates the /routes route that lists all the routes configured

services.AddRouteAnalyzerInDevelopment(this.CurrentEnvironment);

// Add the managers

services.AddManagers();

// Background services

services.AddBackgroundService<StorageSetupService>();

// Log

this.Logger.LogTrace("Application services configuration completed.");
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// Validation

SmartGuard.NotNull(() => app, app);
SmartGuard.NotNull(() => env, env);

// Log

this.Logger.LogTrace("Application configuration starting.");

// Error handling (Telemetry)

app.UseTelemetryExceptionHandler();

// Authentication

app.UseAuthentication();

// Register the throttling middleware

app.UseThrottling();

// MVC

app.UseMvc(
(routes) =>
{
// Routes analyzer

routes.MapRouteAnalyzerInDevelopment(env);
});

// Log

this.Logger.LogTrace("Application configuration completed.");
}

相关中间件代码如下:
internal class ClientRateMiddleware : IClientRateThrottlingMiddleware
{
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
(...)
Claim claim = context.User.FindFirst("client_id");
// Claim is always null here because the Jwt handler has not run
(...)
}
}

最佳答案

好的,所以我想我已经破解了这个。我认为@Hugo Quintela Ribeiro 是正确的,授权仅发生在 [Authorize] 过滤器被点击时,或者在为整个应用程序设置授权的情况下,当没有 [Allow Anonymous] 的 Controller 被点击时。这当然发生在 Controller 上,而不是中间件上。
事实证明,您实际上可以强制在中间件中进行身份验证。我尝试了以下几件事,但没有成功。

await context.AuthenticateAsync();
await context.AuthenticateAsync("Custom"); //name of my jwt auth
最后,我不得不注入(inject) IAuthorizationPolicyProvider 和 IPolicyEvaluator 来获取默认策略并对其进行身份验证。
using cpDataORM;
using cpDataServices.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Policy;
using Microsoft.AspNetCore.Http;
using System.Globalization;
using System.Threading.Tasks;

namespace cpDataASP.Middleware
{
public class LocalizationAndCurrencyMiddleware
{
private readonly RequestDelegate _next;

public LocalizationAndCurrencyMiddleware(RequestDelegate next)
{
_next = next;
}



public async Task Invoke(HttpContext context, IUserService _userService, ILoginContextAccessor loginContext, IAuthorizationPolicyProvider policyProvider, IPolicyEvaluator policyEvaluator)
{
var policy = await policyProvider.GetDefaultPolicyAsync();
await policyEvaluator.AuthenticateAsync(policy, context);
var localizationResources = await _userService.GetLocalizationResources();
loginContext.Timezone = localizationResources.Timezone;
CultureInfo.CurrentCulture = localizationResources.Culture;

await _next.Invoke(context);
}
}
}

关于identityserver4 - 如何强制运行身份验证,以便主体可用于其他 ASP.NET Core 中间件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49589840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com