Unable to cast object of type System.Security.Claims.ClaimsPrincipal to type Microsoft.IdentityModel.Claims.IClaimsPrincipal

user3240560 picture user3240560 · Mar 10, 2014 · Viewed 11.5k times · Source

I am developing one MVC4 application which authenticate corp domain users using ADFS and i have written the code and i am getting the error like below, am i not getting claims ?

System.InvalidCastException: Unable to cast object of type 'System.Security.Claims.ClaimsPrincipal' to type 'Microsoft.IdentityModel.Claims.IClaimsPrincipal'.

    public ActionResult Index()
    {
        try
        {

            IClaimsPrincipal principal = (IClaimsPrincipal)Thread.CurrentPrincipal;
            IClaimsIdentity identity = (IClaimsIdentity)principal.Identity;
            if (String.IsNullOrEmpty(identity.Claims[0].Value.Split('@')[0]))
            {
                ViewData["Message"] = string.Format("You are email is :{0}", identity.Claims[0].Value.Split('@')[0]);

            }
            else
            {
                ViewData["Message"] = "You are not getting any claims";
            }
        }
        catch (Exception ex)
        {
            ViewData["Message"] = "Something wrong.";
        }
        return View();
    }

Answer

astaykov picture astaykov · Mar 10, 2014

What you observe is result of mixing .NET 3.5 WIF (Microsoft.IdentityModel) and WIF 4.0 (System.IdentityModel & System.Security). What I suggest is:

  1. Remove reference to Microsoft.IdentityModel.* assemblies in your project
  2. Add reference to System.IdentityModel & System.IdentityModel.Services assemblies
  3. Fix using statements
  4. Fix references to Microsoft.IdentityModel in your Web.Config

Do a backup copy of your project before doing this, because, if you haven't done this before, you might end up with a lot of error and not working code. But the main idea is that you have to get rid of all and any Microsoft.IdentityModel references and you will be good.