def setup_authorization(self): """ SET token_default token_scope_hr_r token_scope_brk_plus header_auth_default header_auth_scope_hr_r header_auth_scope_brk_plus """ jwks = get_keyset() assert len(jwks['keys']) > 0 key = next(iter(jwks['keys'])) now = int(time.time()) header = { 'alg': 'ES256', # algorithm of the test key 'kid': key.key_id } token_default = JWT(header=header, claims={ 'iat': now, 'exp': now + 600, 'scopes': [] }) token_scope_hr_r = JWT(header=header, claims={ 'iat': now, 'exp': now + 600, 'scopes': [authorization_levels.SCOPE_HR_R] }) token_scope_brk_plus = JWT(header=header, claims={ 'iat': now, 'exp': now + 600, 'scopes': [ authorization_levels.SCOPE_HR_R, authorization_levels.SCOPE_BRK_RS, authorization_levels.SCOPE_BRK_RSN ] }) token_default.make_signed_token(key) self.token_default = token_default.serialize() self.header_auth_default = { AUTH_HEADER: "Bearer {}".format(self.token_default) } token_scope_hr_r.make_signed_token(key) self.token_scope_hr_r = token_scope_hr_r.serialize() self.header_auth_scope_hr_r = { AUTH_HEADER: "Bearer {}".format(self.token_scope_hr_r) } token_scope_brk_plus.make_signed_token(key) self.token_scope_brk_plus = token_scope_brk_plus.serialize() self.header_auth_scope_brk_plus = { AUTH_HEADER: "Bearer {}".format(self.token_scope_brk_plus) }
def _get_userinfo(self, *args, **kwargs): info = self.cfg.datastore.getUserInfo(self.api_token['userinfocode']) if not info: return self._respond_error('invalid_request', 'No userinfo for token') if self.api_client.get('userinfo_signed_response_alg'): cherrypy.response.headers.update({ 'Content-Type': 'application/jwt' }) if self.api_client.get('userinfo_signed_response_alg') == 'RS256': sig = JWT(header={'alg': 'RS256', 'kid': self.cfg.idp_sig_key_id}, claims=info) else: return self._respond_error( 'unsupported_response_type', 'Requested signing mech not supported') # FIXME: Maybe add other algorithms in the future sig.make_signed_token(self.cfg.keyset.get_key( self.cfg.idp_sig_key_id)) # FIXME: Maybe encrypt in the future info = sig.serialize(compact=True) if isinstance(info, dict): info = json.dumps(info) return info
def client_assertion(self, audience: str, lifetime: int = 60, jti: str = None) -> str: iat = int(datetime.now().timestamp()) exp = iat + lifetime if jti is None: jti = str(uuid4()) elif callable(jti): jti = jti() if not isinstance(jti, str): jti = str(jti) jwt = JWT( header={ "alg": self.alg, "kid": self.kid }, claims={ "iss": self.client_id, "sub": self.client_id, "aud": audience, "iat": iat, "exp": exp, "jti": jti, }, ) jwt.make_signed_token(self.private_jwk) assertion: str = jwt.serialize() return assertion
def setUpAuthorization(self): """ SET token_scope_hr to use with: self.client.credentials( HTTP_AUTHORIZATION='Bearer {}'.format(self.token_scope_hr)) """ jwks = get_keyset() assert len(jwks['keys']) > 0 key = next(iter(jwks['keys'])) now = int(time.time()) headers = { 'alg': 'ES256', # algorithm of the test key 'kid': key.key_id } payload = { 'iat': now, 'exp': now + 600, 'scopes': [settings.SCOPE_HR_R] } token = JWT(header=headers, claims=payload) token.make_signed_token(key) self.token_scope_hr_r = token.serialize()
def _get_token(self, scope): """ Obtain a token to be used in the http client: self.client.credentials( HTTP_AUTHORIZATION='Bearer {}'.format(token)) """ jwks = get_keyset() assert len(jwks["keys"]) > 0 key = next(iter(jwks["keys"])) now = int(time.time()) header = {"alg": "ES256", "kid": key.key_id} # algorithm of the test key token = JWT( header=header, claims={ "iat": now, "exp": now + 600, "scopes": [scope], }, ) token.make_signed_token(key) return token.serialize()
def make_sig_kem(name, value, key, alg): header = {'kid': key.key_id, 'alg': alg} claims = {'sub': name, 'exp': int(time.time() + (5 * 60))} if value is not None: claims['value'] = value jwt = JWT(header, claims) jwt.make_signed_token(key) return jwt.serialize(compact=True)
def make_sig_kem(name, value, key, alg): header = {'kid': key.key_id, 'alg': alg} claims = {'sub': name, 'exp': int(time.time() + (5 * 60))} if value is not None: claims['value'] = value jwt = JWT(header, claims) jwt.make_signed_token(key) return jwt.serialize(compact=True)
def make_sig_kem(name, value, key, alg): header = {"kid": key.key_id, "alg": alg} claims = {"sub": name, "exp": int(time.time() + (5 * 60))} if value is not None: claims["value"] = value S = JWT(header, claims) S.make_signed_token(key) return S.serialize(compact=True)
def _fetcher(scopes): kid = "2aedafba-8170-4064-b704-ce92b7c89cc6" key = jwks.get_keyset().get_key(kid) token = JWT(header={ "alg": "ES256", "kid": kid }, claims=fetch_tokendata(scopes)) token.make_signed_token(key) return token.serialize()
def _serialize(self): """Performs the serialization but the object is not "frozen" by setting ``_serialization``. """ h = { "alg": "ES256", "kid": thumbprint(self._key), } jwt = JWT(header=h, claims=self.toJson()) jwt.make_signed_token(self._key) log.debug("Block signed with key thumbprint: {}".format(h["kid"])) return jwt.serialize()
def jwt_token(self, scope): now = int(time.time()) scopes = [scope] if isinstance(scope, str) else [] payload = {'iat': now, 'exp': now + 300, 'scopes': scopes} headers = { 'alg': 'ES256', # algorithm of the test key 'kid': self.kid } token = JWT(header=headers, claims=payload) token.make_signed_token(self.key) return token.serialize()
def create_secure_metadata(key_id, key_secret, expires, metadata): header = { "alg": "dir", "enc": "A256GCM", "kid": key_id, } claims = { "exp": int(expires), "ninchat.com/metadata": metadata, } key = JWK(kty="oct", k=key_secret) token = JWT(header=header, claims=claims) token.make_encrypted_token(key) return token.serialize()
def create_webpush_jwt(endpoint_url): with open(WEBPUSH_PRIVATE_KEY_PATH, 'rb') as key: jwk = JWK.from_pem(key.read()) jwt = JWT(header={ 'typ': 'JWT', 'alg': 'ES256' }, claims={ 'sub': f'mailto:{notifications["support_email"]}', 'exp': str(int(time() + WEBPUSH_EXPIRATION)), 'aud': f'{endpoint_url.scheme}://{endpoint_url.netloc}' }, algs=['ES256']) jwt.make_signed_token(jwk) return jwt.serialize()
def make_idtoken(client, claims): '''Make a serialized JWT targeted for this client''' if client.idtoken_algo == client.ALGO_HMAC: header = {'alg': 'HS256'} jwk = JWK(kty='oct', k=base64url(client.client_secret.encode('utf-8'))) elif client.idtoken_algo == client.ALGO_RSA: header = {'alg': 'RS256'} jwk = get_first_rsa_sig_key() header['kid'] = jwk.key_id if jwk is None: raise ImproperlyConfigured( 'no RSA key for signature operation in A2_IDP_OIDC_JWKSET') else: raise NotImplementedError jwt = JWT(header=header, claims=claims) jwt.make_signed_token(jwk) return jwt.serialize()
def create_apns_jwt(): with open(path.join(getcwd(), APNS_KEY), 'rb') as key: jwk = JWK.from_pem(key.read()) jwt = JWT(header={ 'typ': 'JWT', 'alg': 'ES256', 'kid': notifications['apns_key_id'] }, claims={ 'iss': notifications['apple_team_id'], 'iat': int(time()) }, algs=['ES256']) jwt.make_signed_token(jwk) return jwt.serialize()
def handle(self, *args: str, **options: Any) -> None: """Main function of this command. It creates a JWT test token with the provided scopes and validity. """ key = JWK(**json.loads(settings.JWKS_TEST_KEY)["keys"][0]) scopes = list(set(args)) now = int(time.time()) claims = { "iat": now, "exp": now + options["valid"], "scopes": scopes, "sub": "*****@*****.**", } token = JWT(header={"alg": "ES256", "kid": key.key_id}, claims=claims) token.make_signed_token(key) sys.stdout.write(token.serialize()) sys.stdout.write("\n")
def create_authz_token(scopes=None): if scopes is None: scopes = [] if type(scopes) not in (list, tuple, set): scopes = [scopes] load_jwks(settings.JWKS_TEST_KEY) key = next(iter(_keyset['keys'])) now = int(time.time()) header = {'alg': 'ES256', 'kid': key.key_id} claims = { 'iat': now, 'exp': now + 3600, 'scopes': scopes, 'sub': '*****@*****.**', } token = JWT(header=header, claims=claims) token.make_signed_token(key) return token.serialize()
def token_endpoint_mock(url, request): if urlparse.parse_qs(request.body).get('code') == [code]: id_token = { 'iss': oidc_provider.issuer, 'sub': sub, 'iat': timestamp_from_datetime(now()), 'aud': str(oidc_provider.client_id), 'exp': timestamp_from_datetime(now() + datetime.timedelta(seconds=10)), } if extra_id_token: id_token.update(extra_id_token) if oidc_provider.idtoken_algo == OIDCProvider.ALGO_RSA: jwt = JWT(header={'alg': 'RS256'}, claims=id_token) jwt.make_signed_token(list(oidc_provider_jwkset['keys'])[0]) else: jwt = JWT(header={'alg': 'HS256'}, claims=id_token) jwt.make_signed_token( JWK(kty='oct', k=base64url_encode(oidc_provider.client_secret.encode('utf-8')))) content = { 'access_token': '1234', 'token_type': 'Bearer', 'id_token': jwt.serialize(), } return { 'content': json.dumps(content), 'headers': { 'content-type': 'application/json', }, } else: return { 'content': json.dumps({'error': 'invalid request'}), 'headers': { 'content-type': 'application/json', }, 'status': 400, }
def _get_app_token(self): expired = self._is_token_expired(self._current_app_token_expiry) if expired: now = self._get_now_timestamp() expiry = now + (10 * 60) self._current_app_token_expiry = expiry token = JWT( header={'alg': 'RS256'}, claims={ 'iat': now, 'exp': expiry, 'iss': self._identifier, }, algs=['RS256'], ) token.make_signed_token(JWK.from_pem(self._private_key)) self._current_app_token = token.serialize() return self._current_app_token
def upload_picture(self, picture_stream): """ Upload the file on the given path to the server via HTTP post Uses class configuration to determine the url and key to sign Authorization Bearer token with JWT """ # skip if improperly configured if not self.upload_url or not self.upload_auth_jwk_path: return if not self.upload_auth_jwk: with open(self.upload_auth_jwk_path, 'rb') as f: self.upload_auth_jwk = JWK.from_json(f.read()) try: picture_stream.seek(0) auth_token = JWT(header={'alg': 'EdDSA', 'kid': self.upload_auth_jwk.key_id}, default_claims={'iat':None, 'exp': None}) auth_token.validity=300 auth_token.claims={} auth_token.make_signed_token(self.upload_auth_jwk) auth_header = 'Bearer {}'.format(auth_token.serialize()) response = requests.post( self.upload_url, files={'file': picture_stream}, headers={ 'Authorization': auth_header } ) if not response.ok: logger.error("Error uploading snapshot. Status code {}".format(response.status_code)) except Exception as exc: logger.exception("Error uploading snapshot.") else: # log success logger.info("Snapshot uploaded") finally: picture_stream.seek(0)
def authenticate(client_id, code): payload = { "client_id": client_id, "client_secret": client_secret, "code": code } oauth_response = post("https://github.com/login/oauth/access_token", params=payload) oauth_json = urllib.parse.parse_qs(oauth_response.text) github_token = oauth_json["access_token"][0] user_response = get( "https://api.github.com/user", headers={"Authorization": "token " + github_token}, ) user = user_response.json() now = int(time.time()) token = JWT( header={ "typ": "JWT", "alg": "RS512" }, claims={ "user_id": user["id"], "username": user["login"], "email": user["email"], "github_token": github_token, }, default_claims={ "jti": True, "iss": issuer, "aud": issuer, "nbf": now, "iat": now, "exp": now + token_expiration_time, }, ) token.make_signed_token(key) return {"github_token": github_token, "repoadopt_token": token.serialize()}
def client_assertion(self, audience: str) -> str: iat = int(datetime.now().timestamp()) exp = iat + self.lifetime jti = str(self.jti_gen()) jwk = JWK(kty="oct", k=b64u_encode(self.client_secret)) jwt = JWT( header={"alg": self.alg}, claims={ "iss": self.client_id, "sub": self.client_id, "aud": audience, "iat": iat, "exp": exp, "jti": jti, }, ) jwt.make_signed_token(jwk) assertion: str = jwt.serialize() return assertion
def make_grex_token(): jwks = get_keyset() assert len(jwks['keys']) > 0 key = next(iter(jwks['keys'])) now = int(time.time()) header = { 'alg': 'ES256', # algorithm of the test key 'kid': key.key_id } token = JWT( header=header, claims={ 'iat': now, 'exp': now + 600, 'scopes': ['GREX/R'] } ) token.make_signed_token(key) return token.serialize()
def create_valid_token(app, subject, scopes): jwks = get_keyset() assert len(jwks) > 0 key = next(iter(jwks['keys'])) now = int(time.time()) header = { 'alg': 'ES256', # algorithm of the test key 'kid': key.key_id } token = JWT( header=header, claims={ 'iat': now, 'exp': now + 600, 'scopes': scopes, 'subject': subject }) token.make_signed_token(key) return 'bearer ' + token.serialize()
def generate_jwt_assertion(private_key, claims): rsa_private_key = get_rsa_private_key(private_key) jwkey = JWK.from_pyca(rsa_private_key) token = JWT(header={'alg': 'RS256'}, claims=normalize_claims(claims)) token.make_signed_token(jwkey) return to_unicode(token.serialize(), "UTF-8")
def _respond_success(self, request, client, user, userinfo): # Answer the current request with a successful response. response = {} if client['subject_type'] == 'public': userinfo['sub'] = user.name else: h = hashlib.sha256() if client['sector_identifier_uri']: domain = get_url_hostpart(client['sector_identifier_uri']) else: # We are guaranteed that we either have a sector_identifier_uri # or that the hostpart of all redirect_uris are equal domain = get_url_hostpart(client['redirect_uris'][0]) h.update(domain) h.update(user.name) h.update(self.cfg.idp_subject_salt) userinfo['sub'] = h.hexdigest() claims_userinfo = {} for requested_claim in request['claims']['userinfo']: if requested_claim in userinfo: claims_userinfo[requested_claim] = userinfo[requested_claim] claims_userinfo['sub'] = userinfo['sub'] userinfocode = None if 'openid' in request['scope']: userinfocode = self.cfg.datastore.storeUserInfo(claims_userinfo) if 'token' in request['response_type']: # Asked to return token in authz response # Flows: Hybrid and Implicit token = self.cfg.datastore.issueToken(request['client_id'], user.name, request['scope'], False, userinfocode) del token['token_id'] response['access_token'] = token['access_token'] response['token_type'] = 'Bearer' response['expires_in'] = token['expires_in'] if 'code' in request['response_type']: # Asked to return authorization code # Flows: Authorization code and Hybrid response['code'] = self.cfg.datastore.issueAuthorizationCode( request['client_id'], user.name, request['scope'], userinfo, request['redirect_uri'], userinfocode) if 'openid' in request['scope']: id_token = {} # Build the id_token for requested_claim in request['claims']['id_token']: if requested_claim in userinfo: id_token[requested_claim] = userinfo[requested_claim] id_token['sub'] = userinfo['sub'] id_token['iss'] = self.cfg.endpoint_url id_token['aud'] = request['client_id'] id_token['exp'] = int(time.time()) + 600 id_token['iat'] = int(time.time()) id_token['auth_time'] = userinfo['_auth_time'] if 'nonce' in request: id_token['nonce'] = request['nonce'] id_token['acr'] = '0' id_token['amr'] = json.dumps([]) id_token['azp'] = request['client_id'] if 'code' in response: # Add c_hash id_token['c_hash'] = self._calc_hash(response['code']) if 'access_token' in response: # Add at_hash id_token['at_hash'] = self._calc_hash(response['access_token']) sig = JWT(header={ 'alg': 'RS256', 'kid': self.cfg.idp_sig_key_id }, claims=id_token) # FIXME: Maybe add other algorithms in the future sig.make_signed_token( self.cfg.keyset.get_key(self.cfg.idp_sig_key_id)) # FIXME: Maybe encrypt in the future signed_id_token = sig.serialize(compact=True) if 'code' in response: self.cfg.datastore.storeAuthorizationIDToken( response['code'], signed_id_token) if 'id_token' in request['response_type']: response['id_token'] = signed_id_token return self._respond(request, response)
def setUpAuthorization(self): """ SET token_default token_employee_plus token_scope_brk_rs token_scope_brk_rsn token_scope_brk_ro token_scope_wkpd_rdbu to use with: self.client.credentials( HTTP_AUTHORIZATION='Bearer {}'.format(self.token_employee_plus)) """ jwks = get_keyset() assert len(jwks['keys']) > 0 key = next(iter(jwks['keys'])) now = int(time.time()) header = { 'alg': 'ES256', # algorithm of the test key 'kid': key.key_id } token_default = JWT(header=header, claims={ 'iat': now, 'exp': now + 600, 'scopes': [] }) token_employee_plus = JWT(header=header, claims={ 'iat': now, 'exp': now + 600, 'scopes': [ authorization_levels.SCOPE_BRK_RSN, authorization_levels.SCOPE_BRK_RS, authorization_levels.SCOPE_BRK_RO, authorization_levels.SCOPE_WKPB_RBDU ] }) token_scope_brk_rs = JWT(header=header, claims={ 'iat': now, 'exp': now + 600, 'scopes': [authorization_levels.SCOPE_BRK_RS] }) token_scope_brk_rsn = JWT(header=header, claims={ 'iat': now, 'exp': now + 600, 'scopes': [ authorization_levels.SCOPE_BRK_RSN, authorization_levels.SCOPE_BRK_RS ] }) token_scope_brk_ro = JWT(header=header, claims={ 'iat': now, 'exp': now + 600, 'scopes': [authorization_levels.SCOPE_BRK_RO] }) token_scope_wkpd_rdbu = JWT(header=header, claims={ 'iat': now, 'exp': now + 600, 'scopes': [authorization_levels.SCOPE_WKPB_RBDU] }) token_default.make_signed_token(key) self.token_default = token_default.serialize() token_employee_plus.make_signed_token(key) self.token_employee_plus = token_employee_plus.serialize() token_scope_brk_rs.make_signed_token(key) self.token_scope_brk_rs = token_scope_brk_rs.serialize() token_scope_brk_rsn.make_signed_token(key) self.token_scope_brk_rsn = token_scope_brk_rsn.serialize() token_scope_brk_ro.make_signed_token(key) self.token_scope_brk_ro = token_scope_brk_ro.serialize() token_scope_wkpd_rdbu.make_signed_token(key) self.token_scope_wkpd_rdbu = token_scope_wkpd_rdbu.serialize()
async def write(writer, claims, signing_key): print(f'write: {claims}') msg = JWT(header={'alg': 'RS256'}, claims=claims) msg.make_signed_token(signing_key) writer.write((msg.serialize() + '\n').encode('utf-8')) await writer.drain()