def test_verify_id_token_bad_tokens(self):
        private_key = datafile("privatekey.p12")

        # Wrong number of segments
        self._check_jwt_failure("foo", "Wrong number of segments")

        # Not json
        self._check_jwt_failure("foo.bar.baz", "Can't parse token")

        # Bad signature
        jwt = "foo.%s.baz" % crypt._urlsafe_b64encode('{"a":"b"}')
        self._check_jwt_failure(jwt, "Invalid token signature")

        # No expiration
        signer = crypt.Signer.from_string(private_key)
        audience = "https:#www.googleapis.com/auth/id?client_id=" + "*****@*****.**"
        jwt = crypt.make_signed_jwt(signer, {"aud": "audience", "iat": time.time()})
        self._check_jwt_failure(jwt, "No exp field in token")

        # No issued at
        jwt = crypt.make_signed_jwt(signer, {"aud": "audience", "exp": time.time() + 400})
        self._check_jwt_failure(jwt, "No iat field in token")

        # Too early
        jwt = crypt.make_signed_jwt(signer, {"aud": "audience", "iat": time.time() + 301, "exp": time.time() + 400})
        self._check_jwt_failure(jwt, "Token used too early")

        # Too late
        jwt = crypt.make_signed_jwt(signer, {"aud": "audience", "iat": time.time() - 500, "exp": time.time() - 301})
        self._check_jwt_failure(jwt, "Token used too late")

        # Wrong target
        jwt = crypt.make_signed_jwt(signer, {"aud": "somebody else", "iat": time.time(), "exp": time.time() + 300})
        self._check_jwt_failure(jwt, "Wrong recipient")
  def test_verify_id_token_bad_tokens(self):
    private_key = datafile('privatekey.%s' % self.format)

    # Wrong number of segments
    self._check_jwt_failure('foo', 'Wrong number of segments')

    # Not json
    self._check_jwt_failure('foo.bar.baz',
        'Can\'t parse token')

    # Bad signature
    jwt = 'foo.%s.baz' % crypt._urlsafe_b64encode('{"a":"b"}')
    self._check_jwt_failure(jwt, 'Invalid token signature')

    # No expiration
    signer = self.signer.from_string(private_key)
    audience = 'https:#www.googleapis.com/auth/id?client_id=' + \
        '*****@*****.**'
    jwt = crypt.make_signed_jwt(signer, {
          'aud': 'audience',
          'iat': time.time(),
          }
        )
    self._check_jwt_failure(jwt, 'No exp field in token')

    # No issued at
    jwt = crypt.make_signed_jwt(signer, {
          'aud': 'audience',
          'exp': time.time() + 400,
        }
      )
    self._check_jwt_failure(jwt, 'No iat field in token')

    # Too early
    jwt = crypt.make_signed_jwt(signer, {
        'aud': 'audience',
        'iat': time.time() + 301,
        'exp': time.time() + 400,
    })
    self._check_jwt_failure(jwt, 'Token used too early')

    # Too late
    jwt = crypt.make_signed_jwt(signer, {
        'aud': 'audience',
        'iat': time.time() - 500,
        'exp': time.time() - 301,
    })
    self._check_jwt_failure(jwt, 'Token used too late')

    # Wrong target
    jwt = crypt.make_signed_jwt(signer, {
        'aud': 'somebody else',
        'iat': time.time(),
        'exp': time.time() + 300,
    })
    self._check_jwt_failure(jwt, 'Wrong recipient')
def handleJwt(request):
  """Serves JWT response of appropriate type.

  Args:
    request: A HTTP request object.

  Returns:
    An encoded JWT object as response.
  """
  wob_payload_object = wob_payload.WOB_Payload()
  jwt_type = request.GET.get('type', '')

  if jwt_type == 'loyalty':
    loyalty_obj = loyalty.generate_loyalty_object(
        config.ISSUER_ID, config.LOYALTY_CLASS_ID, config.LOYALTY_OBJECT_ID)
    wob_payload_object.addWalletObjects(loyalty_obj, 'LoyaltyObject')

  elif jwt_type == 'offer':
    offer_obj = offer.generate_offer_object(
        config.ISSUER_ID, config.OFFER_CLASS_ID, config.OFFER_OBJECT_ID)
    wob_payload_object.addWalletObjects(offer_obj, 'OfferObject')

  payload = wob_payload_object.getSaveToWalletRequest()
  signer = crypt.Signer.from_string(key)
  signed_jwt = crypt.make_signed_jwt(signer, payload)

  response = webapp2.Response(signed_jwt)
  response.content_type = 'Application/JWT'
  return response
    def jwt(self, obj, objType):
        loyaltyObjects = []
        giftcardObjects = []
        offerObjects = []

        if objType == 'loyalty':
            loyaltyObjects = [obj]
        elif objType == 'giftcard':
            giftcardObjects = [obj]
        elif objType == 'offer':
            offerObjects = [obj]

        jwt = {
                'iss': config.SERVICE_ACCOUNT,
                'aud': 'google',
                'typ': 'savetoandroidpay',
                'iat':  int(time.time()),
                'payload': {
                        'loyaltyClasses': [], 
                        'giftCardClasses': [],
                        'offerClasses': [],
                        'loyaltyObjects': loyaltyObjects,
                        'giftCardObjects': giftcardObjects,
                        'offerObjects': offerObjects
                },
                'origins' : config.ORIGINS
        }

        with open(config.KEYFILE, 'r') as file_obj:
                client_credentials = json.load(file_obj)
        private_key_pkcs8_pem = client_credentials['private_key']
        signer = crypt.Signer.from_string(private_key_pkcs8_pem)
        signed_jwt = crypt.make_signed_jwt(signer, jwt)
        response = webapp2.Response(signed_jwt)
        return signed_jwt
    def _create_signed_jwt(self):
        private_key = datafile("privatekey.p12")
        signer = crypt.Signer.from_string(private_key)
        audience = "*****@*****.**"
        now = long(time.time())

        return crypt.make_signed_jwt(
            signer, {"aud": audience, "iat": now, "exp": now + 300, "user": "******", "metadata": {"meta": "data"}}
        )
def handleWebservice(request):
  """Creates wallet object according to webservice requests.

  Args:
    request: A HTTP request object.

  Returns:
    Returns object on success, or, error on failure.
  """
  jsonobj = json.loads(request.body)
  first_name = jsonobj['params']['walletUser']['firstName']
  #using first_name to test different error codes
  success = (first_name.startswith('SUCCESS'))

  if success:
    #possible success status codes:
    #SUCCESS, SUCCESS_ACCOUNT_ALREADY_CREATED, SUCCESS_ACCOUNT_ALREADY_LINKED
    jwt = {
      'iss': config.SERVICE_ACCOUNT_EMAIL_ADDRESS,
      'aud': config.AUDIENCE,
      'typ': config.LOYALTY_WEB,
      'iat':  int(time.time()),
      'payload': {
        'loyaltyObjects': [],
        'webserviceResponse': {
          'status': 'SUCCESS'
        },
      }
    }
    linking_id = request.params.get('linkingId')
    loyalty_object_id = linking_id if linking_id else config.LOYALTY_OBJECT_ID
    loyalty_object = loyalty.generate_loyalty_object(
        config.ISSUER_ID, config.LOYALTY_CLASS_ID, loyalty_object_id)
    jwt['payload']['loyaltyObjects'].append(loyalty_object)
  else:
    #possible status error codes:
    #ERROR_INVALID_DATA_FORMAT, ERROR_DATA_ON_MERCHANT_RECORD_DIFFERENT
    #ERROR_INVALID_LINKING_ID, ERROR_PREEXISTING_ACCOUNT_REQUIRES_LINKING, ERROR_ACCOUNT_ALREADY_LINKED
    error_action = 'link' if request.params.get('linkingId') else 'signup'
    jwt = {
      'iss': config.SERVICE_ACCOUNT_EMAIL_ADDRESS,
      'aud': config.AUDIENCE,
      'typ': config.LOYALTY_WEB,
      'iat':  int(time.time()),
      'payload': {
        'webserviceResponse': {
          'status': 'ERROR_INVALID_DATA_FORMAT',
          'invalidField': ['zipcode','phone']
        },
      }
    }
  signer = crypt.Signer.from_string(key)
  signed_jwt = crypt.make_signed_jwt(signer, jwt)
  response = webapp2.Response(signed_jwt)
  response.content_type = 'Application/JWT'
  return response
Exemple #7
0
def handleWebservice(request):
    """Creates wallet object according to webservice requests.

  Args:
    request: A HTTP request object.

  Returns:
    Returns object on success, or, error on failure.
  """
    jsonobj = json.loads(request.body)
    first_name = jsonobj['params']['walletUser']['firstName']
    #using first_name to test different error codes
    success = (first_name.startswith('SUCCESS'))

    if success:
        #possible success status codes:
        #SUCCESS, SUCCESS_ACCOUNT_ALREADY_CREATED, SUCCESS_ACCOUNT_ALREADY_LINKED
        jwt = {
            'iss': config.SERVICE_ACCOUNT_EMAIL_ADDRESS,
            'aud': config.AUDIENCE,
            'typ': config.LOYALTY_WEB,
            'iat': int(time.time()),
            'payload': {
                'loyaltyObjects': [],
                'webserviceResponse': {
                    'status': 'SUCCESS'
                },
            }
        }
        linking_id = request.params.get('linkingId')
        loyalty_object_id = linking_id if linking_id else config.LOYALTY_OBJECT_ID
        loyalty_object = loyalty.generate_loyalty_object(
            config.ISSUER_ID, config.LOYALTY_CLASS_ID, loyalty_object_id)
        jwt['payload']['loyaltyObjects'].append(loyalty_object)
    else:
        #possible status error codes:
        #ERROR_INVALID_DATA_FORMAT, ERROR_DATA_ON_MERCHANT_RECORD_DIFFERENT
        #ERROR_INVALID_LINKING_ID, ERROR_PREEXISTING_ACCOUNT_REQUIRES_LINKING, ERROR_ACCOUNT_ALREADY_LINKED
        error_action = 'link' if request.params.get('linkingId') else 'signup'
        jwt = {
            'iss': config.SERVICE_ACCOUNT_EMAIL_ADDRESS,
            'aud': config.AUDIENCE,
            'typ': config.LOYALTY_WEB,
            'iat': int(time.time()),
            'payload': {
                'webserviceResponse': {
                    'status': 'ERROR_INVALID_DATA_FORMAT',
                    'invalidWalletUserFields': ['zipcode', 'phone']
                },
            }
        }
    signer = crypt.Signer.from_string(key)
    signed_jwt = crypt.make_signed_jwt(signer, jwt)
    response = webapp2.Response(signed_jwt)
    response.content_type = 'Application/JWT'
    return response
Exemple #8
0
 def _generate_assertion(self):
     """Generate the assertion that will be used in the request."""
     now = int(time.time())
     payload = {
         'aud': self.token_uri,
         'scope': self._scopes,
         'iat': now,
         'exp': now + self.MAX_TOKEN_LIFETIME_SECS,
         'iss': self._service_account_email,
     }
     payload.update(self._kwargs)
     return crypt.make_signed_jwt(self._signer, payload)
 def _generate_assertion(self):
     """Generate the assertion that will be used in the request."""
     now = int(time.time())
     payload = {
         "aud": self.token_uri,
         "scope": self._scopes,
         "iat": now,
         "exp": now + self.MAX_TOKEN_LIFETIME_SECS,
         "iss": self._service_account_email,
     }
     payload.update(self._kwargs)
     return crypt.make_signed_jwt(self._signer, payload, key_id=self._private_key_id)
Exemple #10
0
  def _create_signed_jwt(self):
    private_key = datafile('privatekey.%s' % self.format)
    signer = self.signer.from_string(private_key)
    audience = '*****@*****.**'
    now = int(time.time())

    return crypt.make_signed_jwt(signer, {
        'aud': audience,
        'iat': now,
        'exp': now + 300,
        'user': '******',
        'metadata': {'meta': 'data'},
    })
Exemple #11
0
    def _create_signed_jwt(self):
        private_key = datafile('privatekey.' + self.format_)
        signer = self.signer.from_string(private_key)
        audience = '*****@*****.**'
        now = int(time.time())

        return crypt.make_signed_jwt(signer, {
            'aud': audience,
            'iat': now,
            'exp': now + 300,
            'user': '******',
            'metadata': {'meta': 'data'},
        })
        def _generate_assertion(self):
            """Generate the assertion that will be used in the request."""
            now = long(time.time())
            payload = {
                "aud": self.token_uri,
                "scope": self.scope,
                "iat": now,
                "exp": now + SignedJwtAssertionCredentials.MAX_TOKEN_LIFETIME_SECS,
                "iss": self.service_account_name,
            }
            payload.update(self.kwargs)
            logging.debug(str(payload))

            return make_signed_jwt(Signer.from_string(self.private_key, self.private_key_password), payload)
 def _create_token(self, additional_claims=None):
     now = _UTCNOW()
     expiry = now + datetime.timedelta(seconds=self._MAX_TOKEN_LIFETIME_SECS)
     payload = {
         "iat": _datetime_to_secs(now),
         "exp": _datetime_to_secs(expiry),
         "iss": self._service_account_email,
         "sub": self._service_account_email,
     }
     payload.update(self._kwargs)
     if additional_claims is not None:
         payload.update(additional_claims)
     jwt = crypt.make_signed_jwt(self._signer, payload, key_id=self._private_key_id)
     return jwt.decode("ascii"), expiry
Exemple #14
0
def get_signed_jwt(client_id, scope, duration_seconds, key_filename):
    with open(key_filename, 'rb') as f:
        key_data = f.read()

    signer = crypt.OpenSSLSigner.from_string(key_data)

    now = long(time.time())
    jwt_payload = {'aud': 'https://accounts.google.com/o/oauth2/token',
                   'iss': client_id,
                   'scope': scope,
                   'iat': now,
                   'exp': now + duration_seconds}

    jwt = crypt.make_signed_jwt(signer, jwt_payload)
    return jwt
    def _generate_assertion(self):
      """Generate the assertion that will be used in the request."""
      now = long(time.time())
      payload = {
          'aud': self.token_uri,
          'scope': self.scope,
          'iat': now,
          'exp': now + SignedJwtAssertionCredentials.MAX_TOKEN_LIFETIME_SECS,
          'iss': self.service_account_name
      }
      payload.update(self.kwargs)
      logging.debug(str(payload))

      return make_signed_jwt(
          Signer.from_string(self.private_key, self.private_key_password),
          payload)
    def _generate_assertion(self):
      """Generate the assertion that will be used in the request."""
      now = long(time.time())
      payload = {
          'aud': self.token_uri,
          'scope': self.scope,
          'iat': now,
          'exp': now + SignedJwtAssertionCredentials.MAX_TOKEN_LIFETIME_SECS,
          'iss': self.service_account_name
      }
      payload.update(self.kwargs)
      logger.debug(str(payload))

      private_key = base64.b64decode(self.private_key)
      return crypt.make_signed_jwt(crypt.Signer.from_string(
          private_key, self.private_key_password), payload)
Exemple #17
0
    def _GenerateAssertion(self):
        """Generates the signed assertion that will be used in the request.

    Returns:
      string, signed Json Web Token (JWT) assertion.
    """
        now = long(time.time())
        payload = {
            'aud': RpcHelper.TOKEN_ENDPOINT,
            'scope': 'https://www.googleapis.com/auth/identitytoolkit',
            'iat': now,
            'exp': now + RpcHelper.MAX_TOKEN_LIFETIME_SECS,
            'iss': self.service_account_email
        }
        return crypt.make_signed_jwt(
            crypt.Signer.from_string(self.service_account_key), payload)
 def _create_token(self, additional_claims=None):
     now = client._UTCNOW()
     lifetime = datetime.timedelta(seconds=self._MAX_TOKEN_LIFETIME_SECS)
     expiry = now + lifetime
     payload = {
         'iat': _datetime_to_secs(now),
         'exp': _datetime_to_secs(expiry),
         'iss': self._service_account_email,
         'sub': self._service_account_email
     }
     payload.update(self._kwargs)
     if additional_claims is not None:
         payload.update(additional_claims)
     jwt = crypt.make_signed_jwt(self._signer, payload,
                                 key_id=self._private_key_id)
     return jwt.decode('ascii'), expiry
 def _create_token(self, additional_claims=None):
     now = client._UTCNOW()
     lifetime = datetime.timedelta(seconds=self._MAX_TOKEN_LIFETIME_SECS)
     expiry = now + lifetime
     payload = {
         'iat': _datetime_to_secs(now),
         'exp': _datetime_to_secs(expiry),
         'iss': self._service_account_email,
         'sub': self._service_account_email
     }
     payload.update(self._kwargs)
     if additional_claims is not None:
         payload.update(additional_claims)
     jwt = crypt.make_signed_jwt(self._signer,
                                 payload,
                                 key_id=self._private_key_id)
     return jwt.decode('ascii'), expiry
  def _GenerateAssertion(self):
    """Generates the signed assertion that will be used in the request.

    Returns:
      string, signed Json Web Token (JWT) assertion.
    """
    now = long(time.time())
    payload = {
        'aud': RpcHelper.TOKEN_ENDPOINT,
        'scope': 'https://www.googleapis.com/auth/identitytoolkit',
        'iat': now,
        'exp': now + RpcHelper.MAX_TOKEN_LIFETIME_SECS,
        'iss': self.service_account_email
    }
    return crypt.make_signed_jwt(
        crypt.Signer.from_string(self.service_account_key),
        payload)
Exemple #21
0
        def _generate_assertion(self):
            """Generate the assertion that will be used in the request."""
            now = int(time.time())
            payload = {
                'aud': self.token_uri,
                'scope': self.scope,
                'iat': now,
                'exp':
                now + SignedJwtAssertionCredentials.MAX_TOKEN_LIFETIME_SECS,
                'iss': self.service_account_name
            }
            payload.update(self.kwargs)
            #logger.debug(str(payload))

            private_key = base64.b64decode(
                self.private_key)  #.decode(encoding='utf-8')
            return crypt.make_signed_jwt(
                crypt.Signer.from_string(private_key,
                                         self.private_key_password), payload)
Exemple #22
0
def _RefreshServiceAccountIdToken(cred, http_client):
    """Get a fresh id_token for the given service account.

  Args:
    cred: ServiceAccountCredentials, service account for which to refresh the
        id_token.
    http_client: httplib2.Http, the http transport to refresh with.

  Returns:
    str, The id_token if refresh was successful. Otherwise None.
  """
    http_request = http_client.request

    now = int(time.time())
    # pylint: disable=protected-access
    payload = {
        'aud': cred.token_uri,
        'iat': now,
        'exp': now + cred.MAX_TOKEN_LIFETIME_SECS,
        'iss': cred._service_account_email,
        'target_audience': config.CLOUDSDK_CLIENT_ID,
    }
    assertion = crypt.make_signed_jwt(cred._signer,
                                      payload,
                                      key_id=cred._private_key_id)

    body = urllib.parse.urlencode({
        'assertion': assertion,
        'grant_type': _GRANT_TYPE,
    })

    resp, content = http_request(
        cred.token_uri.encode('idna'),
        method='POST',
        body=body,
        headers=cred._generate_refresh_request_headers())
    # pylint: enable=protected-access
    if resp.status == 200:
        d = json.loads(content)
        return d.get('id_token', None)
    else:
        return None
Exemple #23
0
def handleJwt(request):
    """Serves JWT response of appropriate type.

  Args:
    request: A HTTP request object.

  Returns:
    An encoded JWT object as response.
  """
    wob_payload_object = wob_payload.WOB_Payload()
    jwt_type = request.GET.get('type', '')
    obj_id = str(random.randint(1, 100))

    if jwt_type == 'loyalty':
        loyalty_obj = loyalty.generate_loyalty_object(
            config.ISSUER_ID, config.LOYALTY_CLASS_ID,
            config.LOYALTY_OBJECT_ID + obj_id)
        wob_payload_object.addWalletObjects(loyalty_obj, 'LoyaltyObject')

    elif jwt_type == 'offer':
        offer_obj = offer.generate_offer_object(
            config.ISSUER_ID, config.OFFER_CLASS_ID,
            config.OFFER_OBJECT_ID + obj_id)
        wob_payload_object.addWalletObjects(offer_obj, 'OfferObject')

    elif jwt_type == 'giftcard':
        giftcard_obj = giftcard.generate_giftcard_object(
            config.ISSUER_ID, config.GIFTCARD_CLASS_ID,
            config.GIFTCARD_OBJECT_ID + obj_id)
        wob_payload_object.addWalletObjects(giftcard_obj, 'GiftCardObject')

    payload = wob_payload_object.getSaveToWalletRequest()
    signer = crypt_google.RSASigner.from_service_account_file(
        config.SERVICE_ACCOUNT_PRIVATE_KEY)
    signed_jwt = crypt.make_signed_jwt(signer, payload)

    response = webapp2.Response(signed_jwt)
    response.content_type = 'Application/JWT'
    return response