Исключение SecurityTokenSignatureKeyNotFoundExceptionC#

Место общения программистов C#
Ответить
Anonymous
 Исключение SecurityTokenSignatureKeyNotFoundException

Сообщение Anonymous »

У меня возникает исключение, когда я пытаюсь получить доступ к защищенной конечной точке:

Microsoft.IdentityModel.Tokens.SecurityTokenSignatureKeyNotFoundException '
в Microsoft.IdentityModel.JsonWebTokens.dll.

Я настраиваю динамический и настраиваемая система аутентификации из файла конфигурации .JSON (ASP.NET 8).
Я вызываю статический метод в Program.cs, который загружает конфигурацию с использованием отражения.
Однако я сталкиваюсь с проблема с преобразованием типа ключа (SymmetricKey).
Как управлять динамической настройкой опций этого типа или других типов?
Спасибо
публичный статический класс AuthenticationConfigurator
{
public static void ConfigurationAuthentications(IServiceCollection Services, IConfiguration Configuration)
{
// Получаем схемы аутентификации из конфигурации
var listAuthenticationSchemes = Configuration
.GetSection("AuthenticationSchemes")
.Get();

Код: Выделить всё

    // Get the default authentication scheme
var defaultScheme = configuration.GetValue("Authentication:DefaultScheme");

// Start configuring authentication
var authBuilder = services.AddAuthentication(defaultScheme);

foreach (var scheme in listAuthenticationSchemes)
{
// Get the handler type from the scheme configuration
var handlerType = Type.GetType(scheme.Handler);

if (handlerType is null)
throw new InvalidOperationException($"Handler type '{scheme.Handler}' not found for scheme '{scheme.Name}'.");

// Get the options type from the handler base type
var optionsType = handlerType.BaseType?.GetGenericArguments()[0];

if (optionsType is null)
throw new InvalidOperationException($"Options type not found for handler '{handlerType.FullName}'.");

// Get the AddScheme method for the authentication builder
var addSchemeMethod = typeof(AuthenticationBuilder)
.GetMethods(BindingFlags.Public | BindingFlags.Instance)
.FirstOrDefault(method => String.Equals(method.Name, nameof(AuthenticationBuilder.AddScheme))
&& method.IsGenericMethod
&& method.GetParameters().Length == 3)?
.MakeGenericMethod(optionsType, handlerType);

if (addSchemeMethod is null)
throw new InvalidOperationException("AddScheme method not found for authentication.");

// Invoke the AddScheme method
addSchemeMethod.Invoke(authBuilder, new object[]
{
scheme.Name,
scheme.Name,
(Action)(options =>
{
if (scheme.Options is null) return;

// Set the options for the handler
foreach (var option in scheme.Options)
{
var property = optionsType.GetProperty(option.Key);
if (property is not null)
{
var convertedValue = Convert.ChangeType(option.Value, property.PropertyType);
property.SetValue(options, convertedValue);
}
}
})
});
}
}
jsonfile

Подробнее здесь: https://stackoverflow.com/questions/792 ... -exception
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»