ClaimsIdentity.Name causing a System.IndexOutOfRangeException

时间:2017-06-09 12:38:23

标签: c# .net asp.net-mvc claims-based-identity identityserver3

I have the following method

private Boolean IsUserAuthenticatedAnonymously()
{
return (HttpContext.Current?.User?.Identity == null || !HttpContext.Current.User.Identity.IsAuthenticated || HttpContext.Current.User.Identity.Name == "SOFTWORKS_INTERNAL");
}

which is causing the following exception:

System.IndexOutOfRangeException: Index was outside the bounds of the array.
at System.Security.Claims.ClaimsIdentity.<get_Claims>d__51.MoveNext()
at System.Security.Claims.ClaimsIdentity.FindFirst(String type)
at System.Security.Claims.ClaimsIdentity.get_Name()
at HttpHandler.IsUserAuthenticatedAnonymously() in HttpHandler.cs:line 187
at HttpHandler.GenerateForwardUri(Uri requestedUri) in HttpHandler.cs:line 300 
at HttpHandler.<SendAsync>d__26.MoveNext() in HttpHandler.cs:line 149

I have a custom HttpModule that, in some cases, creates a GenericPrincipal(). Here's he code:

private void CreateGenericPrincipal(HttpContext context)
{
    try
    {
        string[] roles = new string[0];
        var claims = new List<Claim>();
        claims.Add(new Claim(ClaimTypes.Sid, "SYSTEM"));
        claims.Add(new Claim(ClaimTypes.Name, "SYSTEM"));
        claims.Add(new Claim(ClaimTypes.NameIdentifier, "SYSTEM"));

        GenericIdentity genericIdentity = new GenericIdentity("SOFTWORKS_INTERNAL", "Negotiate");
        genericIdentity.AddClaims(claims);
        context.User = new GenericPrincipal(genericIdentity, roles);
        Thread.CurrentPrincipal = context.User;
    }
    catch (Exception ex)
    {
        log.Error("SwAuthenticationModule.CreateGenericPrincipal exception", ex);
    }
}

I'm wondering why HttpContext.Current.User.Identity.Name is causing the above exception. Any help would be really, really appreciated!!

0 个答案:

没有答案