To manage API Keys and Accounts via the API after enforcing Public Key Client Validation, a Main API Key is required. Once Public Key Client Validation is enforced, requests with Auth Tokens will not be successful anymore and by default, API Keys are not permitted to manage Accounts or Keys.
The required keys can be created in the Console by selecting Main
as the Key Type.
To create a new Subaccount and make a successful API request, the newly created account needs to be primed with its own API Key and Public Key. Only Main API Keys have the permissions to execute the required steps below.
_52import com.twilio.rest.accounts.v1.credential.PublicKey;_52import com.twilio.rest.api.v2010.Account;_52import com.twilio.rest.api.v2010.account.NewKey;_52import com.twilio.http.TwilioRestClient;_52import com.twilio.http.ValidationClient;_52import java.security.PrivateKey;_52_52public class NewSubAccount {_52 private static final String ACCOUNT_SID = CredStore.getEnv("TWILIO_ACCOUNT_SID");_52 private static final String API_KEY = CredStore.getEnv("TWILIO_MAIN_KEY");_52 private static final String API_SECRET = CredStore.getEnv("TWILIO_MAIN_SECRET");_52 private static final String PUBLIC_KEY_SID = CredStore.getEnv("TWILIO_PUBLIC_KEY_SID");_52 private static final PrivateKey PRIVATE_KEY = CredStore.getPrivateKey();_52 private static final String PUBLIC_KEY = CredStore.getPublicKey();_52_52 public static void main(String[] args) {_52_52 //Create client with Main Account Credentials_52 TwilioRestClient client = new TwilioRestClient.Builder(API_KEY, API_SECRET)_52 .accountSid(ACCOUNT_SID)_52 .httpClient(new ValidationClient(ACCOUNT_SID, PUBLIC_KEY_SID, API_KEY, PRIVATE_KEY))_52 .build();_52_52 //Create new Subaccount _52 Account myAccount = Account.creator().setFriendlyName("PKCV Account").create(client);_52 String myAccountSid = myAccount.getSid();_52_52 //Seed API Key_52 NewKey myKey = NewKey.creator(myAccountSid).setFriendlyName("PKCV Key").create(client);_52_52 //Seed Public Key_52 PublicKey myPubKey = PublicKey.creator(PUBLIC_KEY)_52 .setAccountSid(myAccountSid)_52 .setFriendlyName("Seed PK")_52 .create(client);_52_52 //Create a client for new Subaccount_52 TwilioRestClient newClient = new TwilioRestClient.Builder(myKey.getSid(), myKey.getSecret())_52 .accountSid(myAccountSid)_52 .httpClient(new ValidationClient(myAccountSid, myPubKey.getSid(), myKey.getSid(), PRIVATE_KEY))_52 .build();_52_52 //Make API call with new account and list public key sid(s) assigned to account_52 Iterable pks = PublicKey.reader().read(newClient);_52 for (PublicKey pk : pks) {_52 System.out.println("key: " + pk.getSid() + " - friendlyName: " + pk.getFriendlyName());_52 }_52_52 //Clean up_52 Account.updater(myAccountSid).setStatus(Account.Status.CLOSED).update(client);_52 }_52}
The Console also supports creating API Keys and adding Public Keys for new Subaccounts.