8000 Adds JWT refresh to http example. (#1190) · lukebjerring/python-docs-samples@66f06fd · GitHub 8000
[go: up one dir, main page]

Skip to content

Commit 66f06fd

Browse files
gguussJon Wayne Parrott
authored andcommitted
Adds JWT refresh to http example. (GoogleCloudPlatform#1190)
* Adds JWT refresh to http example. * Fixes style
1 parent f352ca6 commit 66f06fd

File tree

4 files changed

+148
-65
lines changed

4 files changed

+148
-65
lines changed

iot/api-client/http_example/README.md

Lines changed: 0 additions & 50 deletions
This file was deleted.
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
.. This file is automatically generated. Do not edit this file directly.
2+
3+
Google Cloud IoT Core API Python Samples
4+
===============================================================================
5+
6+
This directory contains samples for Google Cloud IoT Core API. `Google Cloud IoT Core`_ allows developers to easily integrate Publish and Subscribe functionality with devices and programmatically manage device authorization.
7+
The following example runs the sample using the project ID `blue-jet-123` and the device name `my-python-device`:
8+
9+
python cloudiot_http_example.py \
10+
--registry_id=my-registry \
11+
--project_id=blue-jet-123 \
12+
--device_id=my-python-device \
13+
--message_type=event \
14+
--algorithm=RS256 \
15+
--private_key_file=../rsa_private.pem
16+
17+
18+
19+
20+
.. _Google Cloud IoT Core API: https://cloud.google.com/iot/docs
21+
22+
Setup
23+
-------------------------------------------------------------------------------
24+
25+
26+
Install Dependencies
27+
++++++++++++++++++++
28+
29+
#. Install `pip`_ and `virtualenv`_ if you do not already have them. You may want to refer to the `Python Development Environment Setup Guide`_ for Google Cloud Platform for instructions.
30+
31+
.. _Python Development Environment Setup Guide:
32+
https://cloud.google.com/python/setup
33+
34+
#. Create a virtualenv. Samples are compatible with Python 2.7 and 3.4+.
35+
36+
.. code-block:: bash
37+
38+
$ virtualenv env
39+
$ source env/bin/activate
40+
41+
#. Install the dependencies needed to run the samples.
42+
43+
.. code-block:: bash
44+
45+
$ pip install -r requirements.txt
46+
47+
.. _pip: https://pip.pypa.io/
48+
.. _virtualenv: https://virtualenv.pypa.io/
49+
50+
Samples
51+
-------------------------------------------------------------------------------
52+
53+
HTTP Device Client Example
54+
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
55+
56+
57+
58+
To run this sample:
59+
60+
.. code-block:: bash
61+
62+
$ python cloudiot_http_example.py
63+
64+
usage: cloudiot_http_example.py [-h] --project_id PROJECT_ID --registry_id
65+
REGISTRY_ID --device_id DEVICE_ID
66+
--private_key_file PRIVATE_KEY_FILE
67+
--algorithm {RS256,ES256}
68+
[--cloud_region CLOUD_REGION]
69+
[--ca_certs CA_CERTS]
70+
[--num_messages NUM_MESSAGES] --message_type
71+
{event,state} [--base_url BASE_URL]
72+
[--jwt_expires_minutes JWT_EXPIRES_MINUTES]
73+
74+
Example Google Cloud IoT Core HTTP device connection code.
75+
76+
optional arguments:
77+
-h, --help show this help message and exit
78+
--project_id PROJECT_ID
79+
GCP cloud project name
80+
--registry_id REGISTRY_ID
81+
Cloud IoT Core registry id
82+
--device_id DEVICE_ID
83+
Cloud IoT Core device id
84+
--private_key_file PRIVATE_KEY_FILE
85+
Path to private key file.
86+
--algorithm {RS256,ES256}
87+
The encryption algorithm to use to generate the JWT.
88+
--cloud_region CLOUD_REGION
89+
GCP cloud region
90+
--ca_certs CA_CERTS CA root from https://pki.google.com/roots.pem
91+
--num_messages NUM_MESSAGES
92+
Number of messages to publish.
93+
--message_type {event,state}
94+
Indicates whether the message to be published is a
95+
telemetry event or a device state message.
96+
--base_url BASE_URL Base URL for the Cloud IoT Core Device Service API
97+
--jwt_expires_minutes JWT_EXPIRES_MINUTES
98+
Expiration time, in minutes, for JWT tokens.
99+
100+
101+
102+
103+
.. _Google Cloud SDK: https://cloud.google.com/sdk/
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# This file is used to generate README.rst
2+
3+
product:
4+
name: Google Cloud IoT Core API
5+
short_name: Cloud IoT Core
6+
url: https://cloud.google.com/iot/docs
7+
description: >
8+
`Google Cloud IoT Core`_ allows developers to easily integrate Publish and
9+
Subscribe functionality with devices and programmatically manage device
10+
authorization.
11+
12+
The following example runs the sample using the project ID `blue-jet-123`
13+
and the device name `my-python-device`:
14+
15+
python cloudiot_http_example.py \
16+
--registry_id=my-registry \
17+
--project_id=blue-jet-123 \
18+
--device_id=my-python-device \
19+
--message_type=event \
20+
--algorithm=RS256 \
21+
--private_key_file=../rsa_private.pem
22+
23+
setup:
24+
- install_deps
25+
26+
samples:
27+
- name: HTTP Device Client Example
28+
file: cloudiot_http_example.py
29+
show_help: True
30+
31+
cloud_client_library: false

iot/api-client/http_example/cloudiot_http_example.py

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -35,21 +35,6 @@
3535

3636

3737
def create_jwt(project_id, private_key_file, algorithm):
38-
"""Creates a JWT (https://jwt.io) to authenticate this device.
39-
Args:
40-
project_id: The cloud project ID this device belongs to
41-
private_key_file: A path to a file containing either an RSA256 or
42-
ES256 private key.
43-
algorithm: The encryption algorithm to use. Either 'RS256' or
44-
'ES256'
45-
Returns:
46-
A JWT generated from the given project_id and private key, which
47-
expires in 20 minutes. After 20 minutes, your client will be
48-
disconnected, and a new JWT will have to be generated.
49-
Raises:
50-
ValueError: If the private_key_file does not contain a known key.
51-
"""
52-
5338
token = {
5439
# The time the token was issued.
5540
'iat': datetime.datetime.utcnow(),
@@ -141,6 +126,11 @@ def parse_command_line_args():
141126
'--base_url',
142127
default=_BASE_URL,
143128
help=('Base URL for the Cloud IoT Core Device Service API'))
129+
parser.add_argument(
130+
'--jwt_expires_minutes',
131+
default=20,
132+
type=int,
133+
help=('Expiration time, in minutes, for JWT tokens.'))
144134

145135
return parser.parse_args()
146136

@@ -150,9 +140,18 @@ def main():
150140

151141
jwt_token = create_jwt(
152142
args.project_id, args.private_key_file, args.algorithm)
143+
jwt_iat = datetime.datetime.utcnow()
144+
jwt_exp_mins = args.jwt_expires_minutes
153145

154146
# Publish num_messages mesages to the HTTP bridge once per second.
155147
for i in range(1, args.num_messages + 1):
148+
seconds_since_issue = (datetime.datetime.utcnow() - jwt_iat).seconds
149+
if seconds_since_issue > 60 * jwt_exp_ 6538 mins:
150+
print('Refreshing token after {}s').format(seconds_since_issue)
151+
jwt_token = create_jwt(
152+
args.project_id, args.private_key_file, args.algorithm)
153+
jwt_iat = datetime.datetime.utcnow()
154+
156155
payload = '{}/{}-payload-{}'.format(
157156
args.registry_id, args.device_id, i)
158157

0 commit comments

Comments
 (0)
0