I'm trying to get a unique userid, preferably as a GUID, using AAD as the IDP in an Asp.Net Core app so I can manage identity related activities in a db, using the GUID as a PK, or at least a reference column. I could use some clarity on how to get this id.
I've read:
- The uid (user id) is the same as the sub claim, which changes per app (e.g., v1, v2, adminapp, clientapp, etc. would return different uid's for the same user identity).
- The oid (object id) is unique to the IDP, so it will give the same id for an identity/user regardless of the app. So, I don't know why you would use uid/sub vs. oid if I understand this correctly.
UID's can be obtained via
var userid = User.FindFirstValue(ClaimTypes.NameIdentifier);
But this returns a string and not a GUID... Alternatively, I could use the slightly more error-prone ("uid" not strongly typed like NameIdentifier) statement which does returns a GUID:
var userid = (ClaimsPrincipal.Current.Identities.First().Claims.FirstOrDefault(c => c.Type == "uid")?.Value);
The two statements above do not return the same results, leading me to wonder what exactly is NameIdentifier.
Attempting to get the mysterious oid fails, as no oid claim exists and an exception is thrown:
var userId = Guid.Parse(User.Claims.FirstOrDefault(c => c.Type == "oid")?.Value);
So, what is the recommended practice for obtaining a unique user id for an app that will remain the same throughout variations of the app? UID via FirstOrDefault statement or something else?
Thanks!