Add crypt.Signer.from_service_account_file (#95)
diff --git a/google/auth/crypt.py b/google/auth/crypt.py
index d347600..8d5ac7c 100644
--- a/google/auth/crypt.py
+++ b/google/auth/crypt.py
@@ -227,3 +227,18 @@
raise ValueError('No key could be detected.')
return cls(private_key, key_id=key_id)
+
+ @classmethod
+ def from_service_account_file(cls, filename):
+ """Creates a Signer instance from a service account .json file
+ in Google format.
+
+ Args:
+ filename (str): The path to the service account .json file.
+
+ Returns:
+ Signer: The constructed signer.
+ """
+ from google.auth import _service_account_info
+ _, signer = _service_account_info.from_filename(filename)
+ return signer
diff --git a/tests/test_crypt.py b/tests/test_crypt.py
index 33105e4..fd70f4b 100644
--- a/tests/test_crypt.py
+++ b/tests/test_crypt.py
@@ -13,6 +13,7 @@
# limitations under the License.
import os
+import json
import mock
from pyasn1_modules import pem
@@ -59,6 +60,12 @@
with open(os.path.join(DATA_DIR, 'privatekey.p12'), 'rb') as fh:
PKCS12_KEY_BYTES = fh.read()
+# The service account JSON file can be generated from the Google Cloud Console.
+SERVICE_ACCOUNT_JSON_FILE = os.path.join(DATA_DIR, 'service_account.json')
+
+with open(SERVICE_ACCOUNT_JSON_FILE, 'r') as fh:
+ SERVICE_ACCOUNT_INFO = json.load(fh)
+
def test_verify_signature():
to_sign = b'foo'
@@ -191,3 +198,10 @@
key_bytes = 'bogus-key'
with pytest.raises(ValueError):
crypt.Signer.from_string(key_bytes)
+
+ def test_from_service_account_file(self):
+ signer = crypt.Signer.from_service_account_file(
+ SERVICE_ACCOUNT_JSON_FILE)
+
+ assert signer.key_id == SERVICE_ACCOUNT_INFO['private_key_id']
+ assert isinstance(signer._key, rsa.key.PrivateKey)