Код: Выделить всё
// Set of claims that are initialized in the inline middleware below from request headers and
// used to create the user's identity through the CustomAuthenticationStateProvider
List claimsFromRequestHeaders = new();
// Add the CustomAuthenticationStateProvider to the service collection with a delegate that closes
// over the claimsFromRequestHeaders initialized by the inline middleware below.
builder.Services.AddScoped(implementationFactory: (serviceProvider) =>
{
return new CustomAuthenticationStateProvider(claimsFromRequestHeaders);
});
var app = builder.Build();
// Inline middleware that initializes the claimsFromRequestHeaders collection from the first request.
app.Use(async (context, next) =>
{
// Do not initialize more than once.
if (claimsFromRequestHeaders.Count > 0)
{
await next();
return;
}
// This would be initialized from request headers...
if (context.Request.Headers.TryGetValue("X-Claim-UserId", out var userId))
{
claimsFromRequestHeaders.Add(new Claim(ClaimTypes.NameIdentifier, userId!));
}
if (context.Request.Headers.TryGetValue("X-Claim-UserName", out var userName))
{
claimsFromRequestHeaders.Add(new Claim(ClaimTypes.Name, userName!));
}
await next();
});
< /code>
CustomAuthenticationSttateProvider очень прост: < /p>
///
/// Creates an with claims provider in constructor.
///
public class CustomAuthenticationStateProvider : AuthenticationStateProvider
{
private readonly IReadOnlyCollection _claims;
public CustomAuthenticationStateProvider(IReadOnlyCollection claims)
{
this._claims = claims;
}
public override Task GetAuthenticationStateAsync()
{
var identity = new ClaimsIdentity(this._claims, "Custom Authentication");
var user = new ClaimsPrincipal(identity);
return Task.FromResult(new AuthenticationState(user));
}
}
Вот образец реализации, которая просто жестко претендует на пользовательские претензии, вместо того, чтобы читать их из головок запросов: https://github.com/palomraz/blazorwebap ... .образное/> Обратите внимание, что в приложении используется рендеринг InteractiveServer и что нет addauthentication/AddAuthorization и useauthentication/useauthorization вызовы в стартап -коде. Тем не менее, приложение работает, как и ожидалось.>
Подробнее здесь: https://stackoverflow.com/questions/795 ... st-headers