File: client_validation.py

package info (click to toggle)
python-twilio 6.51.0%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 12,260 kB
  • sloc: python: 128,982; makefile: 51
file content (72 lines) | stat: -rw-r--r-- 2,323 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import os

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.serialization import (
    Encoding,
    PublicFormat,
    PrivateFormat,
    NoEncryption
)

from twilio.http.validation_client import ValidationClient
from twilio.rest import Client


ACCOUNT_SID = os.environ.get('TWILIO_ACCOUNT_SID')
AUTH_TOKEN = os.environ.get('TWILIO_AUTH_TOKEN')

def example():
    """
    Example of using the ValidationClient for signed requests to Twilio.
    This is only available to enterprise customers.

    This will walkthrough creating an API Key, generating an RSA keypair, setting up a
    ValidationClient with these values and making requests with the client.
    """
    client = Client(ACCOUNT_SID, AUTH_TOKEN)

    # Using Client Validation requires using API Keys for auth
    # First create an API key using the standard account sid, auth token client
    print('Creating new api key...')
    api_key = client.new_keys.create(friendly_name='ClientValidationApiKey')

    # Generate a new RSA Keypair
    print('Generating RSA key pair...')
    key_pair = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
        backend=default_backend()
    )
    public_key = key_pair.public_key().public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo)
    private_key = key_pair.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption())

    # Register the public key with Twilio
    print('Registering public key with Twilio...')
    credential = client.accounts.credentials.public_key.create(
        public_key,
        friendly_name='ClientValidationPublicKey'
    )

    # Create a new ValidationClient with the keys we created
    validation_client = ValidationClient(
        ACCOUNT_SID,
        api_key.sid,
        credential.sid,
        private_key
    )

    # Create a REST Client using the validation_client
    client = Client(api_key.sid, api_key.secret, ACCOUNT_SID, http_client=validation_client)

    # Use the library as usual
    print('Trying out client validation...')
    messages = client.messages.list(limit=10)
    for m in messages:
        print('Message {}'.format(m.sid))

    print('Client validation works!')


if __name__ == '__main__':
    example()