Безопасный дескриптор был закрыт при доступе к имени WindowsIdentity.C#

Место общения программистов C#
Anonymous
Безопасный дескриптор был закрыт при доступе к имени WindowsIdentity.

Сообщение Anonymous »

Я разрабатываю внутренний веб-сервис с использованием ASP.Net Core 6. Идентификатор Windows предоставляется приложению IIS при доступе к AuthenticationStateProvider.GetAuthenticationStateAsync().User.
В большинстве случаев эта служба работает так, как ожидалось, но я нашел несколько записей журнала, в которых она вызывала исключение ObjectDisposeException (безопасный дескриптор был закрыт) при доступе к свойству имени этого удостоверения Windows. Не понимаю откуда это, так как не распоряжаюсь этой услугой.
Исключение:

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

System.ObjectDisposedException: Safe handle has been closed.
Object name: 'SafeHandle'.
at System.StubHelpers.StubHelpers.SafeHandleAddRef(SafeHandle pHandle, Boolean& success)
at Interop.Advapi32.GetTokenInformation(SafeAccessTokenHandle TokenHandle, UInt32 TokenInformationClass, SafeLocalAllocHandle TokenInformation, UInt32 TokenInformationLength, UInt32& ReturnLength)
at System.Security.Principal.WindowsIdentity.GetTokenInformation(SafeAccessTokenHandle tokenHandle, TokenInformationClass tokenInformationClass, Boolean nullOnInvalidParam)
at System.Security.Principal.WindowsIdentity.get_User()
at System.Security.Principal.WindowsIdentity.b__55_0()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
at System.Security.Principal.WindowsIdentity.RunImpersonatedInternal(SafeAccessTokenHandle token, Action action)
at System.Security.Principal.WindowsIdentity.GetName()
at Server.Common.Services.ClaimsPrincipalService.GetCurrentUserAccountName()
Это класс, который обращается к AuthenticationStateProvider:

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

public class ClaimsPrincipalService
{
private readonly AuthenticationStateProvider AuthenticationStateProvider;
private readonly Serilog.ILogger Logger;

public ClaimsPrincipalService(AuthenticationStateProvider authenticationStateProvider, Serilog.ILogger logger)
{
AuthenticationStateProvider = authenticationStateProvider;
Logger = logger;
}

public async Task GetCurrentUserAccountName()
{
try
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;

if (user.Identity != null && user.Identity.IsAuthenticated && user.Identity.Name != null)
{
var identityName = user.Identity.Name;
int stop = identityName.IndexOf("\\");
var userId = stop > -1 ? identityName.Substring(stop + 1, identityName.Length - stop - 1) : string.Empty;
userId = userId.ToUpper();
return userId;
}
else
{
Logger.Warning("User Identity/Authentication could not be verified");
}
}
catch (Exception ex)
{
Logger.Error(ex, "Exception during GetClaimsPrincipalDataAsync method");
}
return null;
}
}
В Program.cs это добавляется как служба с ограниченной областью действия:

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

builder.Services.AddScoped();
Я также экспериментировал с использованием ServerAuthenticationStateProvider, но эта служба недоступна, хотя я использую серверную часть blazor.

Подробнее здесь: https://stackoverflow.com/questions/785 ... wsidentity

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