I am trying to remove the brackets in the email claims that I getfrom Azure AD B2C.
After the user logs in I decode user's token and get the email from that. But the email that I get has brackets in it. The email looks like this ["[email protected]"] which its make it ugly when I save it to the database.
Is there some setting to remove the brackets from the email claim?
JObject ParseIdToken(string idToken)
{
// Get the piece with actual user info
idToken = idToken.Split('.')[1];
idToken = Base64UrlDecode(idToken);
return JObject.Parse(idToken);
}
private string Base64UrlDecode(string s)
{
s = s.Replace('-', '+').Replace('_', '/');
s = s.PadRight(s.Length + (4 - s.Length % 4) % 4, '=');
var byteArray = Convert.FromBase64String(s);
var decoded = Encoding.UTF8.GetString(byteArray, 0, byteArray.Count());
return decoded;
}
public void CacheUser(AuthenticationResult ar)
{
JObject user = ParseIdToken(ar.IdToken);
var cache = new CachedUsers
{
FullName = user["name"]?.ToString(),
Email = user["emails"]?.ToString()
};
BlobCache.LocalMachine.InsertObject("usercached", cache);
}
That is my code to get the email. Why does the email have brackets? I guess the problem is not in my code but maybe there is some setting in Azure AD B2C that makes it like that because when I try to decode the token from https://jwt.io/ it returns the same, the email with brackets. Has anyone experienced this?
Here is the payload from jwt.io 
You can see the difference between name and the email. The email has brackets like this [ ] and what I want to know is how to remove those brackets and make it like name. Because when I get the email in Xamarin forms it has those brackets too so instead of [email protected] it get like this ["[email protected]"]
In JSON, brackets denote arrays. See this basic JSON Arrays documentation.
While not easily exposed via the Azure AD B2C UI, it's technically possible for a user to have multiple emails linked to their account, which is why the email claim is an array.
The reason the string you are seeing is shown as ["[email protected]"] is because you are calling .ToString() on a JSON array. You need to modify your code to obtain a specific element of that array, for example, the first element:
public void CacheUser(AuthenticationResult ar)
{
JObject user = ParseIdToken(ar.IdToken);
var cache = new CachedUsers
{
FullName = user["name"]?.ToString(),
Email = user["emails"]?.FirstOrDefault()?.ToString()
};
BlobCache.LocalMachine.InsertObject("usercached", cache);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With