1
+ import os
2
+
3
+ from cryptography .hazmat .backends import default_backend
4
+ from cryptography .hazmat .primitives .asymmetric import rsa
5
+ from cryptography .hazmat .primitives .serialization import (
6
+ Encoding ,
7
+ PublicFormat ,
8
+ PrivateFormat ,
9
+ NoEncryption
10
+ )
11
+
12
+ from twilio .http .validation_client import ValidationClient
13
+ from twilio .rest import Client
14
+
15
+
16
+ ACCOUNT_SID = os .environ .get ('TWILIO_ACCOUNT_SID' )
17
+ AUTH_TOKEN = os .environ .get ('TWILIO_AUTH_TOKEN' )
18
+
19
+ def example ():
20
+ """
21
+ Example of using the ValidationClient for signed requests to Twilio.
22
+ This is only available to enterprise customers.
23
+
24
+ This will walkthrough creating an API Key, generating an RSA keypair, setting up a
25
+ ValidationClient with these values and making requests with the client.
26
+ """
27
+ client = Client (ACCOUNT_SID , AUTH_TOKEN )
28
+
29
+ # Using Client Validation requires using API Keys for auth
30
+ # First create an API key using the standard account sid, auth token client
31
+ print ('Creating new api key...' )
32
+ api_key = client .new_keys .create (friendly_name = 'ClientValidationApiKey' )
33
+
34
+ # Generate a new RSA Keypair
35
+ print ('Generating RSA key pair...' )
36
+ key_pair = rsa .generate_private_key (
37
+ public_exponent = 65537 ,
38
+ key_size = 2048 ,
39
+ backend = default_backend ()
40
+ )
41
+ public_key = key_pair .public_key ().public_bytes (Encoding .PEM , PublicFormat .PKCS1 )
42
+ private_key = key_pair .private_bytes (Encoding .PEM , PrivateFormat .PKCS8 , NoEncryption ())
43
+
44
+ # Register the public key with Twilio
45
+ print ('Registering public key with Twilio...' )
46
+ credential = client .accounts .credentials .public_key .create (
47
+ public_key ,
48
+ friendly_name = 'ClientValidationPublicKey'
49
+ )
50
+
51
+ # Create a new ValidationClient with the keys we created
52
+ validation_client = ValidationClient (
53
+ ACCOUNT_SID ,
54
+ api_key .sid ,
55
+ credential .sid ,
56
+ private_key
57
+ )
58
+
59
+ # Create a REST Client using the validation_client
60
+ client = Client (api_key .sid , api_key .secret , ACCOUNT_SID , http_client = validation_client )
61
+
62
+ # Use the library as usual
63
+ print ('Trying out client validation...' )
64
+ messages = client .messages .list (limit = 10 )
65
+ for m in messages :
66
+ print ('Message {}' .format (m .sid ))
67
+
68
+ print ('Client validation works!' )
69
+
70
+
71
+ if __name__ == '__main__' :
72
+ example ()
0 commit comments