def __init__(self): self.__instance = JWT() self.__algorithm = "RS256" with open(get_root() + 'rsa_private.pem', 'rb') as fh: self.__signing_key = jwk_from_pem(fh.read()) with open(get_root() + 'rsa_public.pem', 'rb') as fh: self.__verifying_key = jwk_from_pem(fh.read())
def verify_token(token): jwt = JWT() with open('public.pem', 'rb') as fh: public_key = jwk_from_pem(fh.read()) payload = jwt.decode(token, public_key) return payload
def decorated_function(*args, **kwargs): token = request.headers.get('token') responseUnauthorized = make_response(jsonify({ 'status': 'ng', 'data': {} }), 401) if token == None: #Return unauthorize response return responseUnauthorized try: with open('rsa_public_key.pem', 'rb') as fh: verifying_key = jwk_from_pem(fh.read()) jwt = JWT() data = jwt.decode(token, verifying_key) logging.info(data) user_id = data['data']['user_id'] user = User.query.filter_by(id = user_id).first() user = user_schema.dump(user).data if user == {}: return responseUnauthorized request.user = user except: #Return unauthorize response return responseUnauthorized return f(*args, **kwargs)
def genToken(appid): import json import datetime import time import calendar import requests from jwt import ( JWT, jwk_from_pem, ) exp = datetime.datetime.utcnow() + datetime.timedelta(minutes=10) exp = calendar.timegm(exp.timetuple()) message = { 'iat': int(time.time()), 'exp': exp, 'iss': 39888, } with open('now-deploy.pem', 'rb') as fh: signing_key = jwk_from_pem(fh.read()) jwt = JWT() compact_jws = jwt.encode(message, signing_key, 'RS256') data = { 'Authorization': f'Bearer {compact_jws}', 'Accept': 'application/vnd.github.machine-man-preview+json' } r = requests.post( url=f"https://api.github.com/app/installations/{appid}/access_tokens", headers=data) data = r.json() token = data["token"] return token
def start(): global jwt_key_priv global jwt_key_pub # load public and private keys for jwt with open('auth.key', 'rb') as prv_kf: jwt_key_priv = jwk_from_pem(prv_kf.read()) with open('auth.key.pub', 'rb') as pub_kf: jwt_key_pub = jwk_from_pem(pub_kf.read()) # run flask app app.run(debug=False) # run socket server socketio.run(app)
def jwk_from(file_read: bytes, read_as: str = 'json') -> AbstractJWKBase: # For PEM read if read_as == 'pem': return jwk_from_pem(file_read) else: return jwk_from_dict(json.loads(str(file_read)))
def get_bearer_token(): if not GH_APP_PRIVATE_KEY.exists(): return None app_id = os.environ['GITHUB_APP_ID'] with open(GH_APP_PRIVATE_KEY, 'rb') as fh: private_key = jwt.jwk_from_pem(fh.read()) i = jwt.JWT() # Generate the JWT payload = { # issued at time, 60 seconds in the past to allow for clock drift 'iat': jwt.utils.get_int_from_datetime( datetime.now(timezone.utc) - timedelta(seconds=60)), # JWT expiration time (10 minute maximum) 'exp': jwt.utils.get_int_from_datetime( datetime.now(timezone.utc) + timedelta(minutes=10)), # GitHub App's identifier 'iss': app_id, } return i.encode(payload, private_key, alg="RS256")
def verify_access_token(access_token): with open('public.pem', 'rb') as f: public_key = jwk_from_pem(f.read()) #pk = jwk_from_pen(open('/home/rcolomina/public.pem','rb').read()) try: #print(access_token) #print(public_key) print("type of access_token:", type(access_token)) pk = jwk_from_pem(open('/home/rcolomina/public.pem', 'rb').read()) decoded_token = jwt.decode(access_token, pk, algorithms='RS256') print(decoded_token) return True except (e.JWSEncodeError, e.JWSDecodeError): print("Exception happened") return False
def create_jwt(): """ Create a Github App Authentication JSON Web Token Parameters ---------- app_id: string Application ID assigned to the GitHub Application Returns ------- string JSON Web Token (JWT) to use while requesting an GitHub Access Token """ if app_config.APP_DEBUG: print("github.create_jwt: start") app_id, app_secret, installation_id = get_gh_app_data() if not app_id or not app_secret or not installation_id: if app_config.APP_DEBUG: print( "github.remove_org_member: app_id, app_secret or installation_id not returned" ) raise Exception( "github.create_jwt: get_gh_app_data did not return all required variables" ) time_since_epoch_in_seconds = int(time.time()) payload = { # issued at time 'iat': time_since_epoch_in_seconds, # JWT expiration time 'exp': time_since_epoch_in_seconds + (10 * 60), # GitHub App ID 'iss': app_id } gh_app_key = "-----BEGIN RSA PRIVATE KEY-----\r\n" gh_app_key += app_secret gh_app_key += "\r\n-----END RSA PRIVATE KEY-----" try: enc_gh_app_key = bytes(gh_app_key, 'UTF-8') signing_key = jwt.jwk_from_pem(enc_gh_app_key) except Exception as e: raise Exception("github.create_jwt: Github Private Key not loaded") instance = jwt.JWT() token = instance.encode(payload, signing_key, alg='RS256') if app_config.APP_DEBUG: print("github.remove_org_member: end") return token
def get_jwt(pem): # Encodes and returns JWT from jwt import JWT, jwk_from_pem payload = { "iat": int(time.time()), "exp": int(time.time()) + (10 * 60), "iss": os.environ.get("APP_ID"), } jwt = JWT() return jwt.encode(payload, jwk_from_pem(pem), "RS256")
def _get_jwt(self): """ This creates a JWT that can be used to retrieve an authentication token for the Github app.""" jwt = JWT() now = int(time.time()) payload = { "iat": now, "exp": now + (60), "iss": self.noisepage_repo_client.app_id } private_key = jwk_from_pem(str.encode(self.private_key)) return { "jwt": jwt.encode(payload, private_key, alg='RS256'), "exp": payload.get('exp') }
def new_jwt(): """Generate a new JSON Web Token signed by RSA private key.""" with open(GITHUB_PEM_FILE, 'rb') as fp: signing_key = jwt.jwk_from_pem(fp.read()) payload = { 'iat': get_int_from_datetime(datetime.now()), 'exp': get_int_from_datetime( datetime.now(timezone.utc) + timedelta(minutes=10)), 'iss': GITHUB_APP_ID } compact_jws = instance.encode(payload, signing_key, alg='RS256') return compact_jws
class Logger: with open('/opt/ante-jamnet/helper/certs/rsa_private_key.pem', 'rb') as fh: signing_key = jwk_from_pem(fh.read()) def set_request(self, request, action=None): log_date = datetime.now() user_ip = request.remote_addr action_detail = request.json instance = JWT() username = None if 'token' in action_detail: token = action_detail['token'] decode = instance.decode(token, self.signing_key) username = decode['user_name'] del action_detail['token'] if 'action' in action_detail: action = action_detail['action'] module_ip = check_output(['hostname', '--all-ip-addresses' ]).decode("utf-8").strip() system_name = check_output(['hostname']).decode("utf-8").strip() try: PostGre().set_user_log(self.get_serial(), system_name, username, user_ip, log_date, action, json.dumps(action_detail), module_ip) except Exception as e: print(e) @staticmethod def get_serial(): cpu_serial = "0000000000000000" try: f = open('/proc/cpuinfo', 'r') for line in f: if line[0:6] == 'Serial': cpu_serial = line[10:26] f.close() except: cpu_serial = "ERROR000000000" return cpu_serial def set_alarm(self, module_name, action): system_name = check_output(['hostname']).decode("utf-8").strip() log_date = datetime.now() PostGre().set_alarm_log(self.get_serial(), system_name, log_date, action, module_name)
def compute_jwt_token(log, private_file, jwt_token_template=JWT_TEMPLATE, max_timeout_hours=DEFAULT_EXPIRE_TIME): jwt_token_template["exp"] = expires_timestamp(max_timeout_hours) fp_private_file = os.path.realpath(private_file) log.info("Opening private file: " + fp_private_file) log.debug("JWT: " + json.dumps(jwt_token_template)) jwt_token = "not-calculated" jwt_obj = JWT() with open(fp_private_file, "r", encoding="UTF-8") as priv_file_pointer: priv_key = jwk_from_pem(priv_file_pointer.read().encode()) jwt_token = jwt_obj.encode(jwt_token_template, priv_key, 'RS256') log.debug("Calculated JWT token: " + str(jwt_token)) return jwt_token return jwt_token
def make_sign_api_signature_upload_request(auth_method, access_token, digest, algorithm): jwt_client = JWT() signing_base_url = get_signing_base_path(auth_method) # patch for RSS support whilst requirements for local signing and RSS are different # todo: remove this logic once they are aligned if auth_method == "cis2": pem = DEMO_APP_LOCAL_SIGNING_PRIVATE_KEY.encode("utf-8") sub = DEMO_APP_CLIENT_ID iss = DEMO_APP_CLIENT_ID kid = DEMO_APP_KEY_ID else: # always 'simulated' (this will only support RSS Windows/IOS, smartcard simulated auth will fail as JWTs are different) pem = DEMO_APP_REMOTE_SIGNING_PRIVATE_KEY.encode("utf-8") sub = DEMO_APP_REMOTE_SIGNING_SUBJECT iss = DEMO_APP_REMOTE_SIGNING_ISSUER kid = DEMO_APP_REMOTE_SIGNING_KID signing_key = jwk_from_pem(pem) jwt_request = jwt_client.encode( { "sub": sub, "iss": iss, "aud": signing_base_url, "iat": time.time(), "exp": time.time() + 600, "payload": digest, "algorithm": algorithm, }, signing_key, alg="RS512", optional_headers={"kid": kid}, ) print("Sending Signing Service signature upload request...") print(jwt_request) return httpx.post( f"{signing_base_url}/signaturerequest", headers={ "Content-Type": "text/plain", "Authorization": f"Bearer {access_token}" }, data=jwt_request, verify=False, ).json()
def _ensure_access_token(self): if self.last_refreshed is not None and \ (utils.now() - self.last_refreshed).total_seconds() < self.expires_in: return LOGGER.info("Refreshing access token.") self.last_refreshed = utils.now() if self.auth_method == "oauth2": payload = { "refresh_token": self.refresh_token, "client_id": self.client_id, "client_secret": self.client_secret, "grant_type": "refresh_token" } else: message = { "iss": self.client_email, "scope": "https://www.googleapis.com/auth/analytics.readonly", "aud": "https://oauth2.googleapis.com/token", "exp": math.floor( (self.last_refreshed + timedelta(hours=1)).timestamp()), "iat": math.floor(self.last_refreshed.timestamp()) } signing_key = jwk_from_pem(self.private_key) payload = { "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer", "assertion": JWT().encode(message, signing_key, 'RS256') } token_response = requests.post("https://oauth2.googleapis.com/token", data=payload) token_response.raise_for_status() token_json = token_response.json() self.__access_token = token_json['access_token'] self.expires_in = token_json['expires_in']
def create_jwt(app_id, private_key: bytes, expiration=60): """ Creates a signed JWT, valid for 60 seconds by default. The expiration can be extended beyond this, to a maximum of 600 seconds. :param app_id: Github App ID :param private_key: Github App Private Key in PEM format :param expiration: int :return: an encoded JWT """ now = int(time.time()) payload = { "iat": now, "exp": now + expiration, "iss": int(app_id) } jwt = JWT() return jwt.encode( payload, jwk_from_pem(private_key), "RS256" )
def __init__( self, senseHost, proxyPrefix, userDirectory, userId, privateKeyPath, userGroup=None, ignoreCertErrors=False, rootCA=None, ): self.url = "wss://" + senseHost + "/" + proxyPrefix + "/app/engineData" sslOpts = {} if ignoreCertErrors: sslOpts = {"cert_reqs": ssl.CERT_NONE} else: if rootCA is not None: sslOpts = {'ca_certs': rootCA} else: sslOpts = None payload = {'user': userId, 'directory': userDirectory} if userGroup is not None: payload['group'] = userGroup privateKey = jwk_from_pem(open(privateKeyPath, "rb").read()) token = JWT().encode(key=privateKey, alg='RS256', payload=payload, optional_headers={ 'exp': (datetime.utcnow() + timedelta(minutes=10)).isoformat() }) self.ws = create_connection( self.url, sslopt=sslOpts, header=['authorization: bearer ' + str(token)]) self.session = self.ws.recv()
def post(): data = rest.request.get_json(silent=True) if data is None: response = jsonify({'data': {'success': False, 'code': 403, 'message': 'bad module name'}}) response.status_code = 403 return response username = data['username'] password = data['password'] if username != '!admin!' and password != '!admin!': user = PostGre().check_user(username, password) else: user = ['1'] if len(user) == 0: response = jsonify({'data': {'success': False, 'code': 401, 'message': 'Kullanıcı Adı veya Şifre Hatalı'}}) response.status_code = 401 return response else: instance = JWT() user_id = user[0][0] JWT_ALGORITHM = 'RS512' with open('/opt/ante-jamnet/helper/certs/rsa_private_key.pem', 'rb') as fh: signing_key = jwk_from_pem(fh.read()) payload = { 'iss': 'Ante-Jamnet', 'user_name': username, 'iat': get_int_from_datetime(datetime.now(timezone.utc)), 'user_id': user_id, 'exp': get_int_from_datetime( datetime.now(timezone.utc) + timedelta(hours=240)), } jwt_token = instance.encode(payload, signing_key, JWT_ALGORITHM) try: PostGre().set_user_token(user_id, username, jwt_token) except Exception as e: print(e) return {'data': {'success': True, 'token': jwt_token}}
import logging import sys from jwt import jwt, jwk_from_pem from util.common import get_config, Config if __name__ == "__main__": logging.basicConfig(stream=sys.stdout, level=logging.INFO) private_key_path = get_config(Config.PRIVATE_KEY) # Payload format used when DNA-S calls IM API payload = { "userId": 12345, "iby": "Common Services", "type": "user_access_token", "username": "******", "tenantid": 6789, "tenantId": 6789, "iat": 1610458439, "exp": 1610480039, } with open(private_key_path, "rb") as fh: key = jwk_from_pem(fh.read()) encoded_jwt = jwt.JWT().encode(payload=payload, key=key, alg="RS256") print(encoded_jwt)
from flask_session import Session from flask.ext.github import GitHub from jwt import jwk_from_pem from requests.auth import HTTPBasicAuth from util import io from util.user import User from db import insert, fetch from bson import ObjectId import requests, json, urllib, pymongo, sys, secrets app = Flask(__name__) sess = Session() with open("config.json", 'r') as config_file: client_config = json.load(config_file) with open("private-key.pem", 'rb') as priv_key_file: priv_key = jwk_from_pem(priv_key_file.read()) http_auth_username = client_config['HTTP_AUTH_USERNAME'] http_auth_secret = client_config['HTTP_AUTH_SECRET'] http_auth = HTTPBasicAuth(http_auth_username, http_auth_secret) app.config['SESSION_TYPE'] = 'mongodb' app.config['GITHUB_CLIENT_ID'] = client_config['GITHUB_CLIENT_ID'] app.config['GITHUB_CLIENT_SECRET'] = client_config['GITHUB_CLIENT_SECRET'] sess.init_app(app) github = GitHub(app) @app.route('/login') def login(): if session.get('user_token', None) is None: return redirect( 'https://github.com/login/oauth/authorize?client_id=96d3befa08fccb14296c&scope=user&state=report',
def get_header(self): with open(f'{test_dir}/test_jwt_privatekey.pem', 'rb') as fh: private_key = jwk_from_pem(fh.read()) header = JWT().encode(token, private_key, 'RS256') header = {"Authorization": f" Bearer {header}"} return header
def get_access_token(): try: debug_print('Starting app authentication against GitHub', func_name='get_access_token') pem_file_path = str(current_app.config.get('GITHUB_APP_PEM_PATH')) # This is the flow to request data about the app # https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app time_now = int(time.time()) payload = { 'iss': current_app.config.get('GITHUB_APP_ID'), 'iat': time_now, 'exp': time_now + (5 * 60) } debug_print('Opening PEM file for reading. PEM file path: {0}'.format(pem_file_path), func_name='get_access_token') with open(pem_file_path, 'rb') as f: private_key = jwk_from_pem(f.read()) f.close() debug_print('PEM file successfully read', func_name='get_access_token') jwtoken = JWT() jwsignature = jwtoken.encode(payload, private_key, 'RS256') api_app_url = 'https://api.github.com/app/installations' headers = { 'Authorization': 'Bearer {0}'.format(str(jwsignature)), 'Accept': 'application/vnd.github.machine-man-preview+json' } debug_print('Sending GET request to {0}'.format(api_app_url), func_name='get_access_token') response = requests.get(api_app_url, headers=headers) # Here starts the flow to acquire the access token # https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-an-installation if response.status_code == 200: #OK debug_print('GET request to {0} returned 200 OK'.format(api_app_url), func_name='get_access_token') json_content = json.loads(response.content.decode('utf8')) debug_print('Response content: {0}'.format(json_content), func_name='get_access_token') if type(json_content) is list: debug_print('Content is list...', func_name='get_access_token') # the github account may have more than one application installed for l in json_content: debug_print('json within content list: {0}'.format(l), func_name='get_access_token') if l.get('app_id') == int(current_app.config.get('GITHUB_APP_ID')): debug_print('found the right json: {0}'.format(l), func_name='get_access_token') json_content = l break debug_print('json_content before posting to the access tokens url: {0}'.format(json_content), func_name='get_access_token') access_tokens_url = json_content.get('access_tokens_url') debug_print('Sending POST request to {0}'.format(access_tokens_url), func_name='get_access_token') response = requests.post(access_tokens_url, headers=headers) if response.status_code == 201: #OK Created debug_print('POST request to {0} returned 201 OK Created'.format(access_tokens_url), func_name='get_access_token') json_content = json.loads(response.content.decode('utf8')) return json_content.get('token') else: debug_print('Unexpected response from github api with code: {0}'.format(response.status_code), func_name='get_access_token') except JSONDecodeError: debug_print('ERROR reading json returned by github... (JSONDecodeError)', func_name='get_access_token') except OSError: debug_print('ERROR reading PEM file...', func_name='get_access_token') except: # debug_print('ERROR authorizing app...', func_name='get_access_token') return False else: debug_print('GitHub app authentication successful!', func_name='get_access_token') return True
def requires_authorization(scope, decrypt_key, logger=None): if scope is None: log(logger, logging.ERROR, 'Current scope must be specified.') raise ValueError('Current scope must be specified.') if decrypt_key is None: log(logger, logging.ERROR, 'Decrypt key must be specified.') raise ValueError('Decrypt key must be specified.') decoder = JWT() verifying_key = jwk_from_pem(decrypt_key) def inner_function(function): @wraps(function) def wrapper(*args, **kwargs): if request.headers.get('authorization') is None: log(logger, logging.ERROR, 'Authorization code not provided.') return abort(401, 'Authorization code not provided.') authorization_header = request.headers['Authorization'].split(' ') if len(authorization_header) != 2: log(logger, logging.ERROR, 'Invalid Authorization JWT format.') return abort(403, 'Invalid Authorization JWT format.') if authorization_header[0].lower().strip() != 'bearer': log(logger, logging.ERROR, 'Invalid Authorization type.') return abort(403, 'Invalid Authorization type.') jwt = authorization_header[1] try: payload = decoder.decode(jwt, verifying_key) except: log(logger, logging.ERROR, 'Invalid JWT.') return abort(403, 'Invalid JWT.') # Here all validations # Validate JWT is not expired # return abort(401, 'JWT expired') # Validate the inclusion of scope in JWT if SCOPE_CLAIM in payload.keys(): allowed_scopes = [ scope.strip() for scope in payload[SCOPE_CLAIM].split(',') ] if scope not in allowed_scopes: log(logger, logging.ERROR, 'This scope is not allowed.') return abort(403, 'This scope is not allowed.') else: log(logger, logging.ERROR, 'Scopes not included in JWT.') return abort(403, 'Scopes not included in JWT.') log(logger, logging.INFO, 'Authorization OK.') return function(*args, **kwargs) return wrapper return inner_function
def oauth_callback(provider): oauth = OAuthSignIn.get_provider(provider) social_id, username, email = oauth.callback() logging.info(social_id) logging.info(username) logging.info(email) #Login failed if social_id is None: return jsonify({'status': 'ng', 'data': {}}), 401 #Login success user = User.query.filter_by(email=email).first() user = user_schema.dump(user).data logging.info(user) logging.info(user == {}) logging.info(user != {}) if user == {}: #User not existed logging.info('User not existed') user = User(username, provider, email, None, None, None) logging.info(user) db.session.add(user) db.session.commit() user = { "id": user.id, "username": user.username, "email": user.email, "social_id": user.social_id, "fullname": user.full_name, "phone_number": user.phone_number } else: #User existed logging.info('User existed') logging.info(user) if user['social_id'] == 'facebook' and provider == 'google': logging.info('User facebook sign in via google') else: logging.info('User facebook or google') #Data token data_encode = { 'iss': 'http://localhost:5000', 'sub': 'sudo', 'data': { 'user_id': user['id'] } } #Get private key with open('rsa_private_key.pem', 'rb') as fh: signing_key = jwk_from_pem(fh.read()) #Generate token jwt = JWT() token = jwt.encode(data_encode, signing_key, 'RS256') logging.info(token) #Return response response = make_response(jsonify({'status': 'ok', 'data': user}), 200) response.headers['token'] = token return response
import json import arrow import sys from jwt import ( JWT, jwk_from_dict, jwk_from_pem, ) utc = arrow.utcnow() message = { 'iss': 'Wise2c Technology Co.,Ltd', 'sub': 'License', 'aud': sys.argv[2], 'iat': utc.timestamp, 'exp': utc.shift(days=int(sys.argv[1])).timestamp, } with open('private.pem', 'rb') as fh: signing_key = jwk_from_pem(fh.read()) jwt = JWT() compact_jws = jwt.encode(message, signing_key, 'RS256') print(compact_jws)
def init(cls, config): with open(config.get('jwt.private'), 'rb') as f: JWT.signing_key = jwt.jwk_from_pem(f.read()) with open(config.get('jwt.public'), 'rb') as f: JWT.verifying_key = jwt.jwk_from_pem(f.read())
jwt_expiration = int(config["jwt"]["expiration"]) jwt_lock = None jwt_key = None jwt_obj = jwt.JWT() try: private_file = config["secret"]["jwt_private"] public_file = config["secret"]["jwt_public"] with open(private_file, "rb") as private,\ open(public_file, "rb") as public: jwt_lock = private.read() jwt_key = public.read() jwt_lock = jwt.jwk_from_pem(jwt_lock) jwt_key = jwt.jwk_from_pem(jwt_key) except Exception as e: raise Exception("Unable to read config {} and {}, error {}"\ .format(private_file, public_file, str(e))) hash_key = None hash_auth = None try: hash_file = config["hash"]["key"] with open(hash_file, "rb") as hash: hash_key = hash.read() hash_auth = int(config["hash"]["auth"])
def get_public_key(): """Gets the public key from the docker secrets file.""" with open('/run/secrets/public_key', 'rb') as fh: return jwk_from_pem(fh.read())
def generate_credential(**payload): jwt = JWT() with open('private.pem', 'rb') as fh: private_key = jwk_from_pem(fh.read()) token = jwt.encode(payload, private_key, 'RS256') return token