1# Copyright 2022 Google LLC
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""Google API key support.
16This module provides authentication using the `API key`_.
17.. _API key:
18 https://cloud.google.com/docs/authentication/api-keys/
19"""
20
21from google.auth import _helpers
22from google.auth import credentials
23from google.auth import exceptions
24
25
26class Credentials(credentials.Credentials):
27 """API key credentials.
28 These credentials use API key to provide authorization to applications.
29 """
30
31 def __init__(self, token):
32 """
33 Args:
34 token (str): API key string
35 Raises:
36 ValueError: If the provided API key is not a non-empty string.
37 """
38 super(Credentials, self).__init__()
39 if not token:
40 raise exceptions.InvalidValue("Token must be a non-empty API key string")
41 self.token = token
42
43 @property
44 def expired(self):
45 return False
46
47 @property
48 def valid(self):
49 return True
50
51 @_helpers.copy_docstring(credentials.Credentials)
52 def refresh(self, request):
53 return
54
55 def apply(self, headers, token=None):
56 """Apply the API key token to the x-goog-api-key header.
57 Args:
58 headers (Mapping): The HTTP request headers.
59 token (Optional[str]): If specified, overrides the current access
60 token.
61 """
62 headers["x-goog-api-key"] = token or self.token
63
64 def before_request(self, request, method, url, headers):
65 """Performs credential-specific before request logic.
66 Refreshes the credentials if necessary, then calls :meth:`apply` to
67 apply the token to the x-goog-api-key header.
68 Args:
69 request (google.auth.transport.Request): The object used to make
70 HTTP requests.
71 method (str): The request's HTTP method or the RPC method being
72 invoked.
73 url (str): The request's URI or the RPC service's URI.
74 headers (Mapping): The request's headers.
75 """
76 self.apply(headers)