def jwt_rs256_encoded(): #read file stage f = open(os.path.abspath(private_key_pemfile_path), "r") lines = f.read() f.close() private_key = '\n'.join(lines.split('\\n')) print(private_key) #encoded stage ''' default request data #header { "alg":"RS256", "typ":"JWT" } #payload { "some":"payload" } ''' jwt.unregister_algorithm('RS256') jwt.register_algorithm('RS256', RSAAlgorithm(RSAAlgorithm.SHA256)) encoded_data = jwt.encode({"some": "payload"}, private_key, algorithm='RS256') return encoded_data
def generate_jwt(bot_username: str, private_key_path: str, use_legacy_crypto: bool = False): # GAE does not allow installation of the cryptography module # Thus, I need to provide a way to fall back to the legacy modules # required by pyJWT if use_legacy_crypto: from jwt.contrib.algorithms.pycrypto import RSAAlgorithm jwt.unregister_algorithm('RS512') jwt.register_algorithm('RS512', RSAAlgorithm(RSAAlgorithm.SHA512)) header = {"typ": "JWT", "alg": "RS512"} # Make sure you're using datetime.utcnow() and not datetime.now() payload = { "sub": bot_username, "exp": datetime.utcnow() + timedelta(minutes=5) } with open(Path(private_key_path), 'r') as keyfile: private_key = keyfile.read() return jwt.encode(payload, private_key, algorithm='RS512', headers=header)
def app(): # Remove any existing pyjwt handlers, as firebase_helper will register # its own. try: jwt.unregister_algorithm('RS256') except KeyError: pass import main main.app.testing = True return main.app.test_client()
def setup_module(_module): """Perform setup of any state specific to the execution of the given module.""" global PRIVATE_KEY global PUBLIC_KEY # private and public key used in tests with open("tests/private_key.pem") as fin: PRIVATE_KEY = fin.read() with open("tests/public_key.pem") as fin: PUBLIC_KEY = fin.read() # just to make sure the following statement does not raise an exception try: jwt.unregister_algorithm('RS256') except KeyError: pass # make sure the RS256 algorithm is initialized jwt.register_algorithm('RS256', RSAAlgorithm(RSAAlgorithm.SHA256))
def include_package(config): """Pyramid package include""" # add translations config.add_translation_dirs('pyams_auth_jwt:locales') # add configuration directives config.add_request_method(create_jwt_token, 'create_jwt_token') config.add_request_method(get_jwt_claims, 'jwt_claims', reify=True) # add route predicate config.add_view_predicate('jwt_object', JWTTokenObjectPredicate) # register new REST API routes config.add_route( REST_TOKEN_ROUTE, config.registry.settings.get('pyams.jwt.rest_token_route', '/api/auth/jwt/token')) config.add_route( REST_VERIFY_ROUTE, config.registry.settings.get('pyams.jwt.rest_verify_route', '/api/auth/jwt/verify')) # update JWT algorithms try: import pycrypto # pylint: disable=import-outside-toplevel,unused-import except ImportError: pass else: from jwt.contrib.algorithms.pycrypto import RSAAlgorithm # pylint: disable=import-outside-toplevel jwt.unregister_algorithm('RS256') jwt.register_algorithm('RS256', RSAAlgorithm(RSAAlgorithm.SHA256)) jwt.unregister_algorithm('RS512') jwt.register_algorithm('RS512', RSAAlgorithm(RSAAlgorithm.SHA512)) try: import ecdsa # pylint: disable=import-outside-toplevel,unused-import except ImportError: pass else: from jwt.contrib.algorithms.py_ecdsa import ECAlgorithm # pylint: disable=import-outside-toplevel jwt.unregister_algorithm('ES256') jwt.register_algorithm('ES256', ECAlgorithm(ECAlgorithm.SHA256)) jwt.unregister_algorithm('ES512') jwt.register_algorithm('ES512', ECAlgorithm(ECAlgorithm.SHA512)) try: import pyams_zmi # pylint: disable=import-outside-toplevel,unused-import config.scan() except ImportError: config.scan(ignore='pyams_auth_jwt.zmi')
def test_verify_jwt_with_none_algorithm(self): """ tests that verify_jwt does not accept jwt that use the none algorithm. """ verifier = self._setup_jwt_auth_verifier(self._public_key_pem) private_key_ret = atlassian_jwt_auth.key.StaticPrivateKeyRetriever( self._example_key_id, self._private_key_pem.decode()) jwt_signer = NoneAlgorithmJwtAuthSigner( issuer=self._example_issuer, private_key_retriever=private_key_ret, ) for algorithm in ['none', 'None', 'nOne', 'nonE', 'NONE']: if algorithm != 'none': jwt.register_algorithm(algorithm, jwt.algorithms.NoneAlgorithm()) jwt_token = jwt_signer.generate_jwt(self._example_aud, alg_header=algorithm) if algorithm != 'none': jwt.unregister_algorithm(algorithm) jwt_headers = jwt.get_unverified_header(jwt_token) self.assertEqual(jwt_headers['alg'], algorithm) with self.assertRaises(jwt.exceptions.InvalidAlgorithmError): verifier.verify_jwt(jwt_token, self._example_aud)
# # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import datetime import os import time # Remove any existing pyjwt handlers, as firebase_helper will register # its own. try: import jwt jwt.unregister_algorithm('RS256') except KeyError: pass import mock import pytest import firebase_helper def test_get_firebase_certificates(testbed): certs = firebase_helper.get_firebase_certificates() assert certs assert len(certs.keys())
from flask_jwt_extended import JWTManager from flask_restful import Api from flask_sqlalchemy import BaseQuery from jwt import register_algorithm, unregister_algorithm from jwt.contrib.algorithms.pycrypto import RSAAlgorithm from sqlalchemy.ext.declarative import DeclarativeMeta from sqlalchemy.orm.collections import InstrumentedList from werkzeug.exceptions import HTTPException from .model import User, db, UserProxy app = Flask(__name__) CORS(app, supports_credentials=True, resources={r"*": {"origins": "*"}}) try: unregister_algorithm('RS256') register_algorithm('RS256', RSAAlgorithm(RSAAlgorithm.SHA256)) except: pass def load_config(filename='config.json'): import json if filename is not None and os.path.exists(filename): with open(filename) as fp: return json.load(fp) print('%s not found; using default configurations' % (filename if filename is not None else 'config.json')) return {}
"""Authorization token handling.""" from flask import current_app, request, g from flask_security import UserMixin import jwt from jwt.contrib.algorithms.pycrypto import RSAAlgorithm from os import getenv from src.utils import fetch_public_key, http_error # just to make sure the following statement does not raise an exception try: jwt.unregister_algorithm('RS256') except KeyError: pass jwt.register_algorithm('RS256', RSAAlgorithm(RSAAlgorithm.SHA256)) def get_audiences(): """Retrieve all JWT audiences.""" return current_app.config.get('BAYESIAN_JWT_AUDIENCE').split(',') def decode_token(token): """Decode JWT token entered by the user.""" if token is None: return http_error('Auth token audience cannot be verified.'), 401 if token.startswith('Bearer '): _, token = token.split(' ', 1)