Get unique ID on the frontend

I am looking for a way to get a unique ID for the user after they sign-in using the normal IC method.

There is a local cookie ic-identity which changes every time a user logs in and logs out.
Is there any way to get a unique id on the frontend from their identity, that is the same each time a user logs in?

Tried this

public shared (msg) func sendId(): async Text {
  return Principal.toText(msg.caller)
};

But then get an error

Reject text: Canister ryjl3-tyaaa-aaaaa-aaaba-cai trapped explicitly: IDL error: byte read out of buffer

Any ideas?

After I cleared that error I get

Canister ryjl3-tyaaa-aaaaa-aaaba-cai trapped explicitly: IDL error: unexpected IDL type when parsing Principal

I was able to resolve this by removing the .dfx directory and rebuilding everything.

Great question! The identity you get back each time is a DelegationIdentity, which will be different every time, but will resolve to a stable principal.

If you are using the auth-client package, you can access the principal with a logged-in auth-client using authClient.getIdentity().getPrincipal().toText();

2 Likes

This is exactly what I was looking for!! :partying_face:

@kpeacock Is this ID ok to treat as public information, or should it be kept secret?

For my purposes, I need an ID associated with each user that I can insert into URLs to track which user is making which request, and to share publicly with other users to track which user made the referral, for example. I was hoping to use one that the IC already associated with a user, but I obviously don’t want to use one that’s supposed to be kept private.

Another option I though of would be to use the user’s Identity Anchor, but I imagine that one is supposed to be kept a little more private, since if someone knows your anchor, they’re one step closer to being able to impersonate you. But at least the Identity Anchor is a number that a user already knows about and has memorized because they need to use it to authorize other computers/browsers.

The benefit of using the Identity Anchor for my purposes is that it’s short. The principal, as text, is awfully long (e.g. pn7z4-vnyzv-z2x4g-joqbh-d435q-ejxg4-zb8vq-2mdz6-ce83g-5whwy-mte). Perhaps there’s a shorter unique id per user? The anonymous user’s principal is pretty short (2vxsx-fae) but it seems like actual users get much longer principals?

I can, of course, avoid all these problems by generating a random, short id per user, or allowing the user to choose a username, but I thought it’d be cool to use an id that the IC already knows about.

Principals are public and free to share. There is no API to access a user’s identity anchor, and it’s not recommended regardless.

You are best off associating principals with user ID’s, usernames, or alternately finding some way to authenticate with one of the IC naming registries - https://icns.id/ or https://icnaming.com/

1 Like