Python google.appengine.api.app_identity.sign_blob() Examples

The following are 27 code examples of google.appengine.api.app_identity.sign_blob(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module google.appengine.api.app_identity , or try the search function .
Example #1
Source File: tokens.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def sign_jwt(aud):
  """Produces a JWT signed with app's service account key."""
  now = int(utils.time_time())
  issuer = utils.get_service_account_name()
  claims = {
      'email': issuer,
      'exp': now + 3600,
      'iat': now,
      'iss': issuer,
      'sub': issuer,
  }
  if aud:
    claims['aud'] = aud
  claims_b64 = b64.encode(utils.encode_to_json(claims))
  payload = '.'.join((_jwt_header_b64, claims_b64))
  # TODO(vadimsh): Use sign_jwt RPC to get JWT header with 'kid' populated.
  _, sig = app_identity.sign_blob(payload)
  return '.'.join((payload, b64.encode(sig))) 
Example #2
Source File: tokens.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def sign_jwt(aud):
  """Produces a JWT signed with app's service account key."""
  now = int(utils.time_time())
  issuer = utils.get_service_account_name()
  claims = {
      'email': issuer,
      'exp': now + 3600,
      'iat': now,
      'iss': issuer,
      'sub': issuer,
  }
  if aud:
    claims['aud'] = aud
  claims_b64 = b64.encode(utils.encode_to_json(claims))
  payload = '.'.join((_jwt_header_b64, claims_b64))
  # TODO(vadimsh): Use sign_jwt RPC to get JWT header with 'kid' populated.
  _, sig = app_identity.sign_blob(payload)
  return '.'.join((payload, b64.encode(sig))) 
Example #3
Source File: tokens.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def sign_jwt(aud):
  """Produces a JWT signed with app's service account key."""
  now = int(utils.time_time())
  issuer = utils.get_service_account_name()
  claims = {
      'email': issuer,
      'exp': now + 3600,
      'iat': now,
      'iss': issuer,
      'sub': issuer,
  }
  if aud:
    claims['aud'] = aud
  claims_b64 = b64.encode(utils.encode_to_json(claims))
  payload = '.'.join((_jwt_header_b64, claims_b64))
  # TODO(vadimsh): Use sign_jwt RPC to get JWT header with 'kid' populated.
  _, sig = app_identity.sign_blob(payload)
  return '.'.join((payload, b64.encode(sig))) 
Example #4
Source File: app_engine.py    From google-auth-library-python with Apache License 2.0 5 votes vote down vote up
def sign(self, message):
        message = _helpers.to_bytes(message)
        _, signature = app_identity.sign_blob(message)
        return signature 
Example #5
Source File: app_engine.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def sign(self, message):
        message = _helpers.to_bytes(message)
        _, signature = app_identity.sign_blob(message)
        return signature 
Example #6
Source File: appengine.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def sign_blob(self, blob):
        """Cryptographically sign a blob (of bytes).

        Implements abstract method
        :meth:`oauth2client.client.AssertionCredentials.sign_blob`.

        Args:
            blob: bytes, Message to be signed.

        Returns:
            tuple, A pair of the private key ID used to sign the blob and
            the signed contents.
        """
        return app_identity.sign_blob(blob) 
Example #7
Source File: app_identity_test.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def test_sign_blob():
    cleartext = 'Curiouser and curiouser!'
    key_name, signature = app_identity.sign_blob(cleartext)
    assert key_name
    assert signature 
Example #8
Source File: app_engine.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def sign(self, message):
        message = _helpers.to_bytes(message)
        _, signature = app_identity.sign_blob(message)
        return signature 
Example #9
Source File: signature.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def sign_blob(blob, deadline=None):
  """Signs a blob using current service's private key.

  Just an alias for GAE app_identity.sign_blob function for symmetry with
  'check_signature'. Note that |blob| can be at most 8KB.

  Returns:
    Tuple (name of a key used, RSA+SHA256 signature).
  """
  # app_identity.sign_blob is producing RSA+SHA256 signature. Sadly, it isn't
  # documented anywhere. But it should be relatively stable since this API is
  # used by OAuth2 libraries (and so changing signature method may break a lot
  # of stuff).
  return app_identity.sign_blob(blob, deadline) 
Example #10
Source File: app_engine.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def sign(self, message):
        message = _helpers.to_bytes(message)
        _, signature = app_identity.sign_blob(message)
        return signature 
Example #11
Source File: signature.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def sign_blob(blob, deadline=None):
  """Signs a blob using current service's private key.

  Just an alias for GAE app_identity.sign_blob function for symmetry with
  'check_signature'. Note that |blob| can be at most 8KB.

  Returns:
    Tuple (name of a key used, RSA+SHA256 signature).
  """
  # app_identity.sign_blob is producing RSA+SHA256 signature. Sadly, it isn't
  # documented anywhere. But it should be relatively stable since this API is
  # used by OAuth2 libraries (and so changing signature method may break a lot
  # of stuff).
  return app_identity.sign_blob(blob, deadline) 
Example #12
Source File: app_engine.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def sign(self, message):
        message = _helpers.to_bytes(message)
        _, signature = app_identity.sign_blob(message)
        return signature 
Example #13
Source File: signature.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def sign_blob(blob, deadline=None):
  """Signs a blob using current service's private key.

  Just an alias for GAE app_identity.sign_blob function for symmetry with
  'check_signature'. Note that |blob| can be at most 8KB.

  Returns:
    Tuple (name of a key used, RSA+SHA256 signature).
  """
  # app_identity.sign_blob is producing RSA+SHA256 signature. Sadly, it isn't
  # documented anywhere. But it should be relatively stable since this API is
  # used by OAuth2 libraries (and so changing signature method may break a lot
  # of stuff).
  return app_identity.sign_blob(blob, deadline) 
Example #14
Source File: app_engine.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def sign(self, message):
        message = _helpers.to_bytes(message)
        _, signature = app_identity.sign_blob(message)
        return signature 
Example #15
Source File: signature.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def sign_blob(blob, deadline=None):
  """Signs a blob using current service's private key.

  Just an alias for GAE app_identity.sign_blob function for symmetry with
  'check_signature'. Note that |blob| can be at most 8KB.

  Returns:
    Tuple (name of a key used, RSA+SHA256 signature).
  """
  # app_identity.sign_blob is producing RSA+SHA256 signature. Sadly, it isn't
  # documented anywhere. But it should be relatively stable since this API is
  # used by OAuth2 libraries (and so changing signature method may break a lot
  # of stuff).
  return app_identity.sign_blob(blob, deadline) 
Example #16
Source File: app_engine.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def sign(self, message):
        message = _helpers.to_bytes(message)
        _, signature = app_identity.sign_blob(message)
        return signature 
Example #17
Source File: app_engine.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def sign(self, message):
        message = _helpers.to_bytes(message)
        _, signature = app_identity.sign_blob(message)
        return signature 
Example #18
Source File: signature.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def sign_blob(blob, deadline=None):
  """Signs a blob using current service's private key.

  Just an alias for GAE app_identity.sign_blob function for symmetry with
  'check_signature'. Note that |blob| can be at most 8KB.

  Returns:
    Tuple (name of a key used, RSA+SHA256 signature).
  """
  # app_identity.sign_blob is producing RSA+SHA256 signature. Sadly, it isn't
  # documented anywhere. But it should be relatively stable since this API is
  # used by OAuth2 libraries (and so changing signature method may break a lot
  # of stuff).
  return app_identity.sign_blob(blob, deadline) 
Example #19
Source File: app_engine.py    From alfred-gmail with MIT License 5 votes vote down vote up
def sign(self, message):
        message = _helpers.to_bytes(message)
        _, signature = app_identity.sign_blob(message)
        return signature 
Example #20
Source File: appengine.py    From alfred-gmail with MIT License 5 votes vote down vote up
def sign_blob(self, blob):
        """Cryptographically sign a blob (of bytes).

        Implements abstract method
        :meth:`oauth2client.client.AssertionCredentials.sign_blob`.

        Args:
            blob: bytes, Message to be signed.

        Returns:
            tuple, A pair of the private key ID used to sign the blob and
            the signed contents.
        """
        return app_identity.sign_blob(blob) 
Example #21
Source File: main.py    From python-docs-samples with Apache License 2.0 5 votes vote down vote up
def get(self):
        message = 'Hello, world!'
        signing_key_name, signature = app_identity.sign_blob(message)
        verified = verify_signed_by_app(message, signature)

        self.response.content_type = 'text/plain'
        self.response.write('Message: {}\n'.format(message))
        self.response.write(
            'Signature: {}\n'.format(base64.b64encode(signature)))
        self.response.write('Verified: {}\n'.format(verified)) 
Example #22
Source File: firetactoe.py    From python-docs-samples with Apache License 2.0 5 votes vote down vote up
def create_custom_token(uid, valid_minutes=60):
    """Create a secure token for the given id.

    This method is used to create secure custom JWT tokens to be passed to
    clients. It takes a unique id (uid) that will be used by Firebase's
    security rules to prevent unauthorized access. In this case, the uid will
    be the channel id which is a combination of user_id and game_key
    """

    # use the app_identity service from google.appengine.api to get the
    # project's service account email automatically
    client_email = app_identity.get_service_account_name()

    now = int(time.time())
    # encode the required claims
    # per https://firebase.google.com/docs/auth/server/create-custom-tokens
    payload = base64.b64encode(json.dumps({
        'iss': client_email,
        'sub': client_email,
        'aud': _IDENTITY_ENDPOINT,
        'uid': uid,  # the important parameter, as it will be the channel id
        'iat': now,
        'exp': now + (valid_minutes * 60),
    }))
    # add standard header to identify this as a JWT
    header = base64.b64encode(json.dumps({'typ': 'JWT', 'alg': 'RS256'}))
    to_sign = '{}.{}'.format(header, payload)
    # Sign the jwt using the built in app_identity service
    return '{}.{}'.format(to_sign, base64.b64encode(
        app_identity.sign_blob(to_sign)[1])) 
Example #23
Source File: main.py    From python-docs-samples with Apache License 2.0 5 votes vote down vote up
def generate_jwt():
    """Generates a signed JSON Web Token using the Google App Engine default
    service account."""
    now = int(time.time())

    header_json = json.dumps({
        "typ": "JWT",
        "alg": "RS256"})

    payload_json = json.dumps({
        "iat": now,
        # expires after one hour.
        "exp": now + 3600,
        # iss is the service account email.
        "iss": SERVICE_ACCOUNT_EMAIL,
        # target_audience is the URL of the target service.
        "target_audience": TARGET_AUD,
        # aud must be Google token endpoints URL.
        "aud": "https://www.googleapis.com/oauth2/v4/token"
    })

    header_and_payload = '{}.{}'.format(
        base64.urlsafe_b64encode(header_json),
        base64.urlsafe_b64encode(payload_json))
    (key_name, signature) = app_identity.sign_blob(header_and_payload)
    signed_jwt = '{}.{}'.format(
        header_and_payload,
        base64.urlsafe_b64encode(signature))

    return signed_jwt 
Example #24
Source File: main.py    From python-docs-samples with Apache License 2.0 5 votes vote down vote up
def generate_jwt():
    """Generates a signed JSON Web Token using the Google App Engine default
    service account."""
    now = int(time.time())

    header_json = json.dumps({
        "typ": "JWT",
        "alg": "RS256"})

    payload_json = json.dumps({
        'iat': now,
        # expires after one hour.
        "exp": now + 3600,
        # iss is the Google App Engine default service account email.
        'iss': DEFAULT_SERVICE_ACCOUNT,
        'sub': DEFAULT_SERVICE_ACCOUNT,
        # Typically, the audience is the hostname of your API. The aud
        # defined here must match the audience in the security configuration
        # in yourOpenAPI spec.
        'aud': 'echo.endpoints.sample.google.com',
        "email": DEFAULT_SERVICE_ACCOUNT
    })

    header_and_payload = '{}.{}'.format(
        base64.urlsafe_b64encode(header_json),
        base64.urlsafe_b64encode(payload_json))
    (key_name, signature) = app_identity.sign_blob(header_and_payload)
    signed_jwt = '{}.{}'.format(
        header_and_payload,
        base64.urlsafe_b64encode(signature))

    return signed_jwt 
Example #25
Source File: appengine.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def sign_blob(self, blob):
        """Cryptographically sign a blob (of bytes).

        Implements abstract method
        :meth:`oauth2client.client.AssertionCredentials.sign_blob`.

        Args:
            blob: bytes, Message to be signed.

        Returns:
            tuple, A pair of the private key ID used to sign the blob and
            the signed contents.
        """
        return app_identity.sign_blob(blob) 
Example #26
Source File: dschat.py    From dschat with MIT License 5 votes vote down vote up
def create_custom_token(uid, valid_minutes=59):
    """Create a secure token for the given id.

    This method is used to create secure custom JWT tokens to be passed to
    clients. It takes a unique id (user_id) that will be used by Firebase's
    security rules to prevent unauthorized access.
    """

    # use the app_identity service from google.appengine.api to get the
    # project's service account email automatically
    client_email = app_identity.get_service_account_name()

    now = int(time.time())
    # encode the required claims
    # per https://firebase.google.com/docs/auth/server/create-custom-tokens
    payload = base64.b64encode(json.dumps({
        'iss': client_email,
        'sub': client_email,
        'aud': _IDENTITY_ENDPOINT,
        'uid': uid,  # the important parameter, as it will be the channel id
        'iat': now,
        'exp': now + (valid_minutes * 60),
    }))
    # add standard header to identify this as a JWT
    header = base64.b64encode(json.dumps({'typ': 'JWT', 'alg': 'RS256'}))
    to_sign = '{}.{}'.format(header, payload)
    # Sign the jwt using the built in app_identity service
    return '{}.{}'.format(to_sign, base64.b64encode(
        app_identity.sign_blob(to_sign)[1])) 
Example #27
Source File: cloud_storage.py    From personfinder with Apache License 2.0 4 votes vote down vote up
def sign_url(self, object_name, url_lifetime):
        """ Generates Cloud Storage signed URL to download Google Cloud Storage
        object without sign in.

        See: https://cloud.google.com/storage/docs/access-control/signed-urls
        
        This only works on a real App Engine app, not in a dev app server.
        
        Args:
            object_name (str): The name of the object which is signed.
            url_lifetime (datetime.timedelta): Lifetime of the signed URL. The
                server rejects any requests received after this time from now.
        """
        if utils.is_dev_app_server():
            # Not working on a dev app server because it doesn't support
            # app_identity.sign_blob(). An alternative implementation would
            # be needed to make it work on a dev app server.
            raise Exception(
                'sign_url only works on a real App Engine app, not on a dev '
                'app server.')

        method = 'GET'
        expiration_time = utils.get_utcnow() + url_lifetime
        expiration_sec = int(time.mktime(expiration_time.timetuple()))
        path = '/%s/%s' % (self.bucket_name, object_name)

        # These are unused in our use case.
        content_md5 = ''
        content_type = ''

        signed_text = '\n'.join([
            method,
            content_md5,
            content_type,
            str(expiration_sec),
            path,
        ])
        (_, signature) = app_identity.sign_blob(signed_text.encode('utf-8'))

        query_params = {
            'GoogleAccessId': app_identity.get_service_account_name(),
            'Expires': str(expiration_sec),
            'Signature': base64.b64encode(signature),
        }
        return 'https://storage.googleapis.com%s?%s' % (path, urllib.urlencode(query_params))