Pergunta

I have a .Net 4.5 MVC4 web app running with ADFS2 authentication. When I go to the web site I am redirected and logged in through the federation server, this part works great.

Now in my application I want to get information about the user. Found plenty of pages describing how I should go about doing this when googling, but I must be missing something as no matter how I do it I am getting blank/empty values back.

I created a test controller that just prints out the information in the two Claims objects I have found on google.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace Web.Controllers
{
    public class ClaimsController : Controller
    {
        public String Index()
        {
            System.Security.Claims.ClaimsPrincipal cp =
                System.Security.Claims.ClaimsPrincipal.Current;

            Microsoft.IdentityModel.Claims.IClaimsIdentity ci =
                Thread.CurrentPrincipal.Identity as Microsoft.IdentityModel.Claims.IClaimsIdentity;

            var o = new
            {
                cp_IsAuthenticated = cp.Identity.IsAuthenticated,
                cp_AuthenticationType = cp.Identity.AuthenticationType,
                cp_Name = cp.Identity.Name,
                //cp_Claims = (new JavaScriptSerializer()).Serialize(cp.Claims), // circlular reference

                ci_IsAuthenticated = ci.IsAuthenticated,
                ci_Label = ci.Label,
                ci_Name = ci.Name
                //ci_Claims = (new JavaScriptSerializer()).Serialize(cp.Claims) // circular reference
            };

            return (new JavaScriptSerializer()).Serialize(o);
        }
    }
}

The result of this is:

{
    "cp_IsAuthenticated":true,
    "cp_AuthenticationType":"Federation",
    "cp_Name":null,

    "ci_IsAuthenticated":true,
    "ci_Label":null,
    "ci_Name":null
}

I am under the impression that "Name" = "" should contain the name I have set in the AD.

Any ideas as to what I am doing wrong or can try? Thanks!

Foi útil?

Solução

The problem was that the ADFS server was not sending the proper claims back in the federation requests.

Once the claims had been set up properly, this code worked for getting the identity of the logged in user

public string GetIdentityUserEmail()
{
    string result = "default.identity@domain.com";

    Microsoft.IdentityModel.Claims.IClaimsIdentity ci =
        Thread.CurrentPrincipal.Identity as Microsoft.IdentityModel.Claims.IClaimsIdentity;

    if (ci != null && ci.Claims != null)
    {
        var accountNameClaim = ci.Claims.Where(x => x.ClaimType.ToLower().EndsWith("windowsaccountname")).FirstOrDefault();
        if (accountNameClaim != null)
            result = accountNameClaim.Value;
    }

    return result;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top