Jonathan Beerhalter
Jonathan Beerhalter

Reputation: 7407

Why does UserPrincipal.FindByIdentity return an error about GUID being 32 bits?

My application uses the UserPrincipal class to determine what groups a user belongs to and then uses that information to determine if a user is authenticated to use my application. Things worked just fine for while, but recently I've started getting an exception

Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)

When calling UserPrincipal.FindByIdentity. It seems like the call is succeeding and the exception is being handled properly, but it makes me nervous that authentication is going to break suddenly in the future. I'm not explicitly creating the GUID anywhere, so I have no idea where the exception is coming from.

Upvotes: 6

Views: 2786

Answers (4)

vkr
vkr

Reputation: 1

Only below way worked for me.

var user = _userManager.FindByNameAsync(HttpContext.User.Identity.Name);

Upvotes: -2

Liam
Liam

Reputation: 29750

My debugging system suddenly started doing this out the blue and I couldn't figure out why. Turned out that when I'd deleted a .user file I seem to of disabled Just My Code debugging and this exception started getting broken into. So check your VS options around this area, you (probably) want this ticked:

enter image description here

Upvotes: 2

Jonathan T-Delorme
Jonathan T-Delorme

Reputation: 61

If you provide the IdentityType, it will not try to consider your value as a Guid, so it will not throw an exception

FindByIdentityWithType(context, typeof(UserPrincipalEx), **IdentityType.SamAccountName**, identityValue);

Upvotes: 4

D Stanley
D Stanley

Reputation: 152624

It's most likely that an exception is being thrown somewhere deep in the Framework code that's trying to initialize some sort of security descriptor from an invalid GUID value. If the framework is catching it and handling it internally I wouldn't worry about it.

Tracing through the Framework code, here is one likely place that it happens:

protected static bool IdentityClaimToFilter(string identity, string identityFormat, ref string filter, bool throwOnFail)
{
  if (identity == null)
    identity = "";
  StringBuilder filter1 = new StringBuilder();
  switch (identityFormat)
  {
    case "ms-guid":
      Guid guid;
      try
      {
        guid = new Guid(identity);
      }
      catch (FormatException ex)
      {
        if (throwOnFail)
          throw new ArgumentException(ex.Message, (Exception) ex);
        else
          return false;
      }
...

Notice that it tries to create a new Guid, and if it fails, an exception is thrown, but the code swallows it and just returns false

Upvotes: 7

Related Questions