Skip to content

Blazor with WindowsIdentity error: Safe handle has been closed #11901

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
sven5 opened this issue Jul 4, 2019 · 6 comments
Closed

Blazor with WindowsIdentity error: Safe handle has been closed #11901

sven5 opened this issue Jul 4, 2019 · 6 comments
Assignees
Labels
area-blazor Includes: Blazor, Razor Components ✔️ Resolution: Duplicate Resolved as a duplicate of another issue investigate

Comments

@sven5
Copy link

sven5 commented Jul 4, 2019

Describe the bug

When using a custom AuthorizationHandler the following Exception will be thrown when navigating through Blazor's router to a secured Page (using @attribute [Authorize(Policy = "customPolicy")])
When directly entering the URL in the browser and hitting Enter this error does not occur.

To Reproduce

Steps to reproduce the behavior:

  1. Using this version of ASP.NET Core: .NET Core 3.0 Preview 6
  2. Run this code - use custom AuthorizationHandler
 public class MyCustomAuthorizationHandler : AuthorizationHandler<LunchMenuRequirement>
    {
        private readonly UserManager<IntranetUser> _userManager;
        private readonly ILogger<MyCustomAuthorizationHandler> _logger;

        public MyCustomAuthorizationHandler(UserManager<IntranetUser> userManager, ILogger<MyCustomAuthorizationHandler> logger)
        {
            _userManager = userManager;
            _logger = logger;
        }
 protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, LunchMenuRequirement requirement)
        {
            if (context.User == null)
            {
                return;
            }
            IntranetUser user = null;
            // **Exception is thrown by calling context.User.Identity.Name**
            if (context.User.Identity is WindowsIdentity)
            {
                _logger.LogDebug($"Principal's Identity is WindowsIdentity {context.User.Identity.Name}");
                var windowsLogin = context.User.Identity.Name;
                user = await _userManager.Users.FirstOrDefaultAsync(u => u.NormalizedWindowsLogin == windowsLogin.ToUpperInvariant());
            }
            else if (context.User.Identity is ClaimsIdentity)
            {
                _logger.LogDebug($"Principal's Identity is ClaimsIdentity {context.User.Identity.Name}");
                user = await _userManager.GetUserAsync(context.User);
            }
            if (user.IsStore)
            {
                context.Succeed(requirement);
            }
            else
            {
                if (await _userManager.IsInRoleAsync(user, "SomeRole"))
                {
                    context.Succeed(requirement);
                }
            }
        }
    }
}
  1. With these arguments '....'
  2. See error
Error: System.ObjectDisposedException: Safe handle has been closed.
Object name: 'SafeHandle'.
   at System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean& success)
   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.<GetName>b__51_0()
   at System.Security.Principal.WindowsIdentity.<>c__DisplayClass67_0.<RunImpersonatedInternal>b__0(Object <p0>)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
   at System.Security.Principal.WindowsIdentity.RunImpersonatedInternal(SafeAccessTokenHandle token, Action action)
   at System.Security.Principal.WindowsIdentity.RunImpersonated(SafeAccessTokenHandle safeAccessTokenHandle, Action action)
   at System.Security.Principal.WindowsIdentity.GetName()
   at xxx.Intranet.WebClient.Extensions.MyCustomAuthorizationHandler.HandleRequirementAsync(AuthorizationHandlerContext context, LunchMenuRequirement requirement) in C:\Projekte\xxx\Intranet-App\src\xxx.Intranet\xxx.Intranet.WebClient\Extensions\MyCustomAuthorizationHandler.cs:line 33
   at Microsoft.AspNetCore.Authorization.AuthorizationHandler`1.HandleAsync(AuthorizationHandlerContext context)
   at Microsoft.AspNetCore.Authorization.DefaultAuthorizationService.AuthorizeAsync(ClaimsPrincipal user, Object resource, IEnumerable`1 requirements)
   at Microsoft.AspNetCore.Components.AuthorizeViewCore.IsAuthorizedAsync(ClaimsPrincipal user)
   at Microsoft.AspNetCore.Components.AuthorizeViewCore.OnParametersSetAsync()
   at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)

Expected behavior

I expect that this error does not occur.

Screenshots

If applicable, add screenshots to help explain your problem.

Additional context

Add any other context about the problem here.
Include the output of dotnet --info

C:\WINDOWS\system32>dotnet --info
.NET Core SDK (gemäß "global.json"):
 Version:   3.0.100-preview6-012264
 Commit:    be3f0c1a03

Laufzeitumgebung:
 OS Name:     Windows
 OS Version:  10.0.17763
 OS Platform: Windows
 RID:         win10-x64
 Base Path:   C:\Program Files\dotnet\sdk\3.0.100-preview6-012264\

Host (useful for support):
  Version: 3.0.0-preview6-27804-01
  Commit:  fdf81c6faf

.NET Core SDKs installed:
  2.1.800-preview-009677 [C:\Program Files\dotnet\sdk]
  2.1.800-preview-009696 [C:\Program Files\dotnet\sdk]
  3.0.100-preview6-012264 [C:\Program Files\dotnet\sdk]

.NET Core runtimes installed:
  Microsoft.AspNetCore.All 2.1.11 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.App 2.1.11 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.AspNetCore.App 3.0.0-preview6.19307.2 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 2.1.11 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 3.0.0-preview6-27804-01 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.WindowsDesktop.App 3.0.0-preview6-27804-01 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]

I will try to create a small sample app to reproduce this issue if you require.

@sven5
Copy link
Author

sven5 commented Jul 5, 2019

Hi folks,

I was able to create a small test case to reproduce this issue.

Regards
Sven

@davidfowl
Copy link
Member

cc @BrennanConroy

@mkArtakMSFT mkArtakMSFT added the area-blazor Includes: Blazor, Razor Components label Jul 5, 2019
@mkArtakMSFT
Copy link
Contributor

@javiercn do you have thoughts regarding this?

@BrennanConroy
Copy link
Member

I'll take a deeper look at this in a bit, but my initial investigation found https://github.com/aspnet/AspNetCore/blob/6f6d0991132cb269bbbc3ac9e8493e7b0de2724d/src/Components/Server/src/Circuits/FixedAuthenticationStateProvider.cs#L26

Which doesn't look quite right. If the underlying SignalR connection closes and then comes back so it uses the same component ID then the User being referenced no longer has a valid lifetime.

@javiercn
Copy link
Member

javiercn commented Jul 5, 2019

@SteveSandersonMS Wouldn't re-validation work here?

@mkArtakMSFT mkArtakMSFT added this to the 3.0.0-preview9 milestone Jul 8, 2019
@mkArtakMSFT mkArtakMSFT added the ✔️ Resolution: Duplicate Resolved as a duplicate of another issue label Jul 12, 2019
@mkArtakMSFT
Copy link
Contributor

This is a dupe of #12051

@ghost ghost locked as resolved and limited conversation to collaborators Dec 3, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
area-blazor Includes: Blazor, Razor Components ✔️ Resolution: Duplicate Resolved as a duplicate of another issue investigate
Projects
None yet
Development

No branches or pull requests

7 participants
@davidfowl @SteveSandersonMS @javiercn @BrennanConroy @sven5 @mkArtakMSFT and others