I see the following code quite often in examples:
fn caller() -> Principal {
let caller = ic_cdk::caller();
if caller == Principal::anonymous() {
panic!("Anonymous principal not allowed to make calls.")
}
caller
}
How do you make sure a Principal is not anonymous? How would you execute this using II?
This is written to prevent the case when someone uses candid ui to call endpoints.
As whenever an endpoint of a canister is called a caller principal is associated with that, but in candid ui case the caller principal is a specific anonymous principal.
To prevent this condition you have to authenticate yourself using either Internet Identity or any other IC wallet.
I made a quick video answer! Here’s the transcript:
user princess_eth asks, “how do you make sure a Principal is not anonymous? How do you execute this using II?”
Great question, let’s take a look!
When you’re interacting with the Internet Computer, by default all of your calls will be anonymous. However, we can attach a cryptographic identity (consisting of a public and private key pair) to our agent, and that will allow us to sign our messages.
Now, if you want to use Internet Identity, you’ll want to use the (@dfinity/auth-client npm package), which will allow you to log in with Internet Identity and get back a “delegation identity” upon success, which you can then use in your HttpAgent as well!
Hope this helps!
And here’s the video: https://youtube.com/shorts/_AKZwwG6Z_k?feature=share
This helps so much! Thank you, appreciate the short. Your team should create more shorts - they are quick and easy to understand.
@h1teshtr1path1, your explanation also makes a lot of sense. I assume it is a security feature as you don’t want non-owner principals to make certain calls.
What is the best way to automatically load your Internet Identity without needing to sign in?
I see that in this documentation on the npm site you can use Secp256k1KeyIdentity to load up a passkey from Internet Identity. However, it is considered risky. Is there a better way? Is there a way to use ECDSAKeyIdentity?
My use case is that I have an application that I want users to call HTTPS Outcalls using my principal. I do not want them to sign in with II and use their cycles to complete an action related to HTTPS Outcalls.
You cannot recreate a Principal from Internet Identity using the seed phrase. It only can be accessed through a login flow.
You can persist the delegation and store it as a string, which the AuthClient does for you by default. The default expiration of 8 hours, but you can extend that out to a week with the maxTimeToLive setting in login.