|
| 1 | +import json |
1 | 2 | from datetime import datetime, timedelta, timezone |
2 | 3 | from typing import Set |
3 | 4 |
|
@@ -63,6 +64,39 @@ def get_grant(self) -> dict: |
63 | 64 | except JoseError as e: |
64 | 65 | raise Exception("Failed to generate JWT assertion: " + str(e)) from e |
65 | 66 |
|
| 67 | + @classmethod |
| 68 | + def from_json(cls, host: str, json_path: str) -> "WebTokenAuthenticator": |
| 69 | + """ |
| 70 | + Create a WebTokenAuthenticatorBuilder instance from a JSON configuration file. |
| 71 | +
|
| 72 | + Expected JSON format: |
| 73 | + { |
| 74 | + "type": "serviceaccount", |
| 75 | + "keyId": "<key-id>", |
| 76 | + "key": "<private-key>", |
| 77 | + "userId": "<user-id>" |
| 78 | + } |
| 79 | +
|
| 80 | + :param host: Base URL for the API endpoints. |
| 81 | + :param json_path: File path to the JSON configuration file. |
| 82 | + :return: A new instance of WebTokenAuthenticator. |
| 83 | + :raises Exception: If the file cannot be read, the JSON is invalid, |
| 84 | + or required keys are missing. |
| 85 | + """ |
| 86 | + try: |
| 87 | + with open(json_path, "r") as file: |
| 88 | + config = json.load(file) |
| 89 | + except Exception as e: |
| 90 | + raise Exception(f"Unable to read JSON file: {json_path}") from e |
| 91 | + |
| 92 | + user_id = config.get("userId") |
| 93 | + private_key = config.get("key") |
| 94 | + if not user_id or not private_key: |
| 95 | + raise Exception("Missing required keys 'userId' or 'key' in JSON file.") |
| 96 | + |
| 97 | + return (WebTokenAuthenticator.builder(host, user_id, private_key) |
| 98 | + .build()) |
| 99 | + |
66 | 100 | @staticmethod |
67 | 101 | def builder(host: str, user_id: str, private_key: str) -> "WebTokenAuthenticatorBuilder": |
68 | 102 | """ |
|
0 commit comments