I am attempting to retrieve some very basic information from Azure B2C, using the Built-In User Attributes and Claims.
I merely want to return
- Given Name
- Surname
- UserId
Its not totally obvious (to me) how B2C is storing this content...
The SignIn/SignOut Policy (User Attirubtes) displays Email Address as a string
but the SignIn/SignOut Policy (Application Claims) displays Email Addresses as a stringCollection
Using the below code, I am attempting to return the 4 above Claims but only the
I have used the JWT.IO to test the return Token and the Claims I'm looking for are there.
Lastly, just to make things even stranger, MS seems to store my Email in a UserName field but doesn't show me an Email Field(s)?
I'm hoping to NOT have to make a seperate call to the Graph API in order to get these 2-3 fields I want.
I'm just hoping someone can help me clarify where my code is going wrong.
var claimsIdentity = (ClaimsIdentity)HttpContext.User.Identity;
var userIdClaim = claimsIdentity.Claims.SingleOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
if (userIdClaim != null)
{
userId = userIdClaim.Value;
ViewData["userId"] = userId;
}
var GivenNameClaim = claimsIdentity.Claims.SingleOrDefault(c => c.Type == ClaimTypes.GivenName);
if (GivenNameClaim != null)
{
GivenName = GivenNameClaim.Value;
ViewData["GivenName"] = GivenName;
}
var SurNameClaim = claimsIdentity.Claims.SingleOrDefault(c => c.Type == ClaimTypes.Surname);
if (SurName != null)
{
SurName = SurNameClaim.Value;
ViewData["Surname"] = SurName;
}
var EmailClaim = claimsIdentity.Claims.SingleOrDefault(c => c.Type == ClaimTypes.Email);
if (Email != null)
{
Email = EmailClaim.Value;
ViewData["Email"] = Email;
}
EDIT
Adding the below to my view helped..
@foreach (Claim claim in User.Claims)
{
<tr>
<td>@claim.Type @claim.Subject</td>
<td>@claim.Value</td>
</tr>
}
It returns
- http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier 6902e027-e475-447c-8f7d-75f4451f85a4
- http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname Tim
- http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname Cadieux
- emails me@email.com
So I have updated me email to the belwo, which now works for 3/4 files, it does not return the collection of emails.
var Claims = User.Claims;
var SurNameClaim = Claims.SingleOrDefault(c => c.Type == ClaimTypes.Surname);
ViewData["Surname"] = SurNameClaim.Value;
var GivenNameClaim = Claims.SingleOrDefault(c => c.Type == ClaimTypes.GivenName);
ViewData["GivenName"] = GivenNameClaim.Value;
var ClientIdClaim = Claims.SingleOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
ViewData["ClientId"] = ClientIdClaim.Value;
var EmailClaim = Claims.SingleOrDefault(c => c.Type == ClaimTypes.Email);
if (EmailClaim != null)
{
ViewData["Email"] = EmailClaim.Value;
}
else
{
ViewData["Email"] = "Is Null";
}