您如何对继承自 的自定义中间件进行单元测试AuthenticationHandler<AuthenticationSchemeOptions>?
我从它继承的自定义类用于基本身份验证。
public class BasicAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
private readonly IProvidePrincipal _principalProvider;
public BasicAuthenticationHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, IProvidePrincipal principalProvider)
: base(options, logger, encoder, clock)
{
_principalProvider = principalProvider;
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
if (Request.Headers.TryGetValue(HeaderNames.Authorization, out StringValues authorizationHeader))
{
if (Credentials.TryParse(authorizationHeader, out Credentials credentials))
{
var principal = await _principalProvider.GetClaimsPrincipalAsync(credentials.Username, credentials.Password, Scheme.Name);
if (principal != null)
{
var ticket = new AuthenticationTicket(principal, Scheme.Name);
return AuthenticateResult.Success(ticket);
}
else
{
return AuthenticateResult.Fail("Basic authentication …Run Code Online (Sandbox Code Playgroud) c# unit-testing asp.net-core asp.net-core-middleware asp.net-core-authenticationhandler
在 ASP.NET Core API 项目中,我需要验证位于与 Authorization 标头不同的标头中的另一个 JWT Bearer 令牌。例如,假设发送一个 GET 请求来获取产品,/api/products并在名为 的标头中包含承载令牌AccessToken。
curl --location --request GET 'https://localhost/api/products' \
--header 'AccessToken: <bearer_token>'
Run Code Online (Sandbox Code Playgroud)
我引用Microsoft.AspNetCore.Authentication.JwtBearer包并在 API 项目中设置身份验证,如下所示:
curl --location --request GET 'https://localhost/api/products' \
--header 'AccessToken: <bearer_token>'
Run Code Online (Sandbox Code Playgroud)
但是,我在JwtBearerOptions Class中找不到有关标头名称的任何内容。
如何配置 JWT 身份验证以从名为“AccessToken”的标头读取 JWT? 是否可以使用 Microsoft.AspNetCore.Authentication.JwtBearer 包?