def token(self): s = JSONWebSignatureSerializer(current_app.config['SECRET_KEY']) return s.dumps({ 'id': self.user_id, 'timestamp': str(self.timestamp) }).decode('utf-8')
def encode_token_for(user): serializer = JSONWebSignatureSerializer(user.access_token) return str(serializer.dumps(user.email), 'utf-8')
def sign(self, value): s = JSONWebSignatureSerializer(self.secret_key) return s.dumps(value).decode()
def verify_password(self, password): s = JSONWebSignatureSerializer(Config.SECRET_KEY) return s.dumps(password) == self.password_hash
def generate_confirmation_token(self, expiration=3600): s = JSONWebSignatureSerializer(current_app.config['SECRET_KEY']) return s.dumps({'confirm': self.id}).decode('utf-8')
def __init__(self, secret_key, expires_in): self.secret_key = secret_key self.expires_in = expires_in self.serializer = JSONWebSignatureSerializer(secret_key)
DB = mongo_client[DB_NAME] GRIDFS = mongo_client[f"{DB_NAME}_gridfs"] MEDIA_CACHE = MediaCache(GRIDFS, USER_AGENT) def _drop_db(): if not DEBUG_MODE: return mongo_client.drop_database(DB_NAME) KEY = get_key(ID, ID + "#main-key", USERNAME, DOMAIN) JWT_SECRET = get_secret_key("jwt") JWT = JSONWebSignatureSerializer(JWT_SECRET) def _admin_jwt_token() -> str: return JWT.dumps( # type: ignore { "me": "ADMIN", "ts": datetime.now().timestamp() }).decode( # type: ignore "utf-8") ADMIN_API_KEY = get_secret_key("admin_api_key", _admin_jwt_token) attachments = [] if PROFILE_METADATA:
def generate_token(self): s = JSONWebSignatureSerializer(app_config.malwarecage.secret_key) return s.dumps({"login": self.user.login, "api_key_id": str(self.id)})
def decom_step2(id): # in this step we work out what steps to perform # then we load this into a list of steps, each step being a dictionary # this is used on the page to list the steps to the user # the list is also used to generate a JSON document which we sign using # app.config['SECRET_KEY'] and then send that onto the page as well. # load the corpus library corpus = Corpus(g.db,app.config) system = cortex.lib.systems.get_system_by_id(id) if system is None: abort(404) actions = [] systemenv = None ## Find the environment that this VM is in based off of the CMDB env if 'cmdb_environment' in system: if system['cmdb_environment'] is not None: for env in app.config['ENVIRONMENTS']: if env['name'] == system['cmdb_environment']: # We found the environment matching the system systemenv = env break ## Is the system linked to vmware? if 'vmware_uuid' in system: if system['vmware_uuid'] is not None: if len(system['vmware_uuid']) > 0: ## The system is linked to vmware - e.g. a VM exists vmobj = corpus.vmware_get_vm_by_uuid(system['vmware_uuid'],system['vmware_vcenter']) if vmobj: if vmobj.runtime.powerState == vim.VirtualMachine.PowerState.poweredOn: actions.append({'id': 'vm.poweroff', 'desc': 'Power off the virtual machine ' + system['name'], 'detail': 'UUID ' + system['vmware_uuid'] + ' on ' + system['vmware_vcenter'], 'data': {'uuid': system['vmware_uuid'], 'vcenter': system['vmware_vcenter']}}) actions.append({'id': 'vm.delete', 'desc': 'Delete the virtual machine ' + system['name'], 'detail': ' UUID ' + system['vmware_uuid'] + ' on ' + system['vmware_vcenter'], 'data': {'uuid': system['vmware_uuid'], 'vcenter': system['vmware_vcenter']}}) ## Is the system linked to service now? if 'cmdb_id' in system: if system['cmdb_id'] is not None: if len(system['cmdb_id']) > 0: if system['cmdb_is_virtual']: if system['cmdb_operational_status'] != u'Deleted': actions.append({'id': 'cmdb.update', 'desc': 'Mark the system as Deleted in the CMDB', 'detail': system['cmdb_id'] + " on " + app.config['SN_HOST'], 'data': system['cmdb_id']}) else: if system['cmdb_operational_status'] != u'Decommissioned': actions.append({'id': 'cmdb.update', 'desc': 'Mark the system as Decommissioned in the CMDB', 'detail': system['cmdb_id'] + " on " + app.config['SN_HOST'], 'data': system['cmdb_id']}) ## Ask infoblox if a DNS host object exists for the name of the system try: refs = corpus.infoblox_get_host_refs(system['name'] + ".soton.ac.uk") if refs is not None: for ref in refs: actions.append({'id': 'dns.delete', 'desc': 'Delete the DNS record ' + ref.split(':')[-1], 'detail': 'Delete the name ' + system['name'] + '.soton.ac.uk - Infoblox reference: ' + ref, 'data': ref}) except Exception as ex: flash("Warning - An error occured when communicating with Infoblox: " + str(type(ex)) + " - " + str(ex),"alert-warning") ## Check if a puppet record exists if 'puppet_certname' in system: if system['puppet_certname'] is not None: if len(system['puppet_certname']) > 0: actions.append({'id': 'puppet.cortex.delete', 'desc': 'Delete the Puppet ENC configuration', 'detail': system['puppet_certname'] + ' on ' + request.url_root, 'data': system['id']}) actions.append({'id': 'puppet.master.delete', 'desc': 'Delete the system from the Puppet Master', 'detail': system['puppet_certname'] + ' on ' + app.config['PUPPET_MASTER'], 'data': system['puppet_certname']}) ## Check if TSM backups exist try: tsm_client = corpus.tsm_get_system(system['name']) #if the TSM client is not decomissioned, then decomission it if tsm_client['DECOMMISSIONED'] is None: actions.append({'id': 'tsm.decom', 'desc': 'Decommission the system in TSM', 'detail': tsm_client['NAME'] + ' on server ' + tsm_client['SERVER'], 'data': {'NAME': tsm_client['NAME'], 'SERVER': tsm_client['SERVER']}}) except requests.execptions.HTTPError as e: flash("Warning - An error occured when communicating with TSM ", "alert-warning") except LookupError: pass # We need to check all (unique) AD domains as we register development # Linux boxes to the production domain tested_domains = set() for adenv in app.config['WINRPC']: try: # If we've not tested this CortexWindowsRPC host before if app.config['WINRPC'][adenv]['host'] not in tested_domains: # Add it to the set of tested hosts tested_domains.update([app.config['WINRPC'][adenv]['host']]) # If an AD object exists, append an action to delete it from that environment if corpus.windows_computer_object_exists(adenv, system['name']): actions.append({'id': 'ad.delete', 'desc': 'Delete the Active Directory computer object', 'detail': system['name'] + ' on domain ' + app.config['WINRPC'][adenv]['domain'], 'data': {'hostname': system['name'], 'env': adenv}}) except Exception as ex: flash("Warning - An error occured when communicating with Active Directory: " + str(type(ex)) + " - " + str(ex), "alert-warning") # If there are actions to be performed, add on an action to raise a ticket to ESM (but not for Sandbox!) if len(actions) > 0 and system['class'] != "play": actions.append({'id': 'ticket.ops', 'desc': 'Raises a ticket with operations to perform manual steps, such as removal from monitoring', 'detail': 'Creates a ticket in Service Now and assigns it to ' + workflow.config['TICKET_TEAM'], 'data': {'hostname': system['name']}}) # Turn the actions list into a signed JSON document via itsdangerous signer = JSONWebSignatureSerializer(app.config['SECRET_KEY']) json_data = signer.dumps(actions) return workflow.render_template("step2.html", actions=actions, system=system, json_data=json_data, title="Decommission Node")
from itsdangerous import JSONWebSignatureSerializer from flask_application import app s = JSONWebSignatureSerializer(app.secret_key) user = s.dumps("prateek") password = s.dumps("flask") with open("credentials.txt", "w+") as f: f.write(":".join([user.decode("utf-8"), password.decode("utf-8")]))
def create_bearer_token(user): serializer = JSONWebSignatureSerializer(current_app.config["SECRET_KEY"]) return serializer.dumps(token_data_schema.dump(user))
def decrypt(text): s = JSONWebSignatureSerializer(SECRET_KEY) try: return s.loads(text) except BadSignature: return {}
def encrypt(text): s = JSONWebSignatureSerializer(SECRET_KEY) return s.dumps(text)
def encrypt(text): if isinstance(text, bytes): value = text.decode("utf-8") s = JSONWebSignatureSerializer(SECRET_KEY) return s.dumps(value)
def sign(self, value): s = JSONWebSignatureSerializer(self.secret_key, algorithm_name='HS256') return s.dumps(value).decode()
def __init__(self,private_key): self.serial = JSONWebSignatureSerializer(private_key)
def generate_token(tenant: Tenant) -> str: s = JSONWebSignatureSerializer(current_app.secret_key, salt="auth") payload = {"repo_ids": [str(o) for o in tenant.repository_ids]} if getattr(tenant, "user_id", None): payload["uid"] = str(tenant.user_id) return s.dumps(payload)
def token_hex(nbytes=None): return urandom(nbytes).hex() # This is the rest controller, it controls every query/update done trough rest (everything in the /api/* site section) # sqlalchemy session used to make query and updates session = db.session # type: Session api = Api() api.prefix = "/api" secret_key = token_hex(32) passw_serializer = JSONWebSignatureSerializer(secret_key) site_image = image.ImageManager() # ---------------- Utility methods ---------------- # Utility methods used to automate the creation and query of resources # Every GET, POST and PUT can use an utility method that discovers which # field to use/update, also checking foreign key constraints (that some databases # could not check). # These methods already handle cases such as resource not found and missing field # and handle them accordingly (ex: source not found -> throw 404) # Get method that throws 404 when # (pidgeon meme) is this strong generic typing?
def generate_token(): token = JSONWebSignatureSerializer('SECRET-KEY').dumps(uuid.uuid1().hex) return token
def query_search_helper(self, body, summary=False, exclude_fields=None, include_fields=None, **kwargs): with_extensions = kwargs.pop('with_extensions', None) custom_filter = kwargs.pop('custom_filter', None) body = body or dict() count = body.get("count", app.config['DEFAULT_COUNT']) current_token = body.get("paginationToken") current_page = body.get("page") filters = UserFilters( self.model_cls, custom_filter, filter=body.get("filter"), order=body.get("order"), term=body.get("term"), include=body.get("include"), exclude=body.get("exclude"), ) field_names = body.get("fields") field_names = tuple(sorted(f for f in field_names if f and f.strip())) if field_names else tuple() identity_json = json.dumps(dict( filter=repr(filters), summary=summary, field_names=field_names, ), sort_keys=True) identity = MD5.new(base64.b64encode(identity_json.encode())).hexdigest() key = current_app.config['SEARCH_KEY'] serializer = JSONWebSignatureSerializer(key) offset = 0 if current_token: try: current_token_payload = serializer.loads(current_token) except BadSignature: self.logger.warning("Bad signature") raise ProblemException(title='Invalid request', detail="Bad pagination token") self.logger.debug('payload=%r identity=%r', current_token_payload, identity) if identity == current_token_payload.get('identity'): offset = current_token_payload.get('offset', 0) if current_page is not None: offset = (current_page - 1) * count else: self.logger.debug('payload=%r identity=%r', None, identity) while True: try: query, total_query, has_extra = self.make_search_queries( self.model_cls, filters, count + 1, offset, field_names, with_extra_columns=True ) except ValueError: self.logger.debug("Problem in the order", exc_info=True) raise ProblemException(title='Invalid request', detail="Problem in the requested order") # Fetch all results and store them in a list # We could do a .count() but that would result in an extra query # Anyway it looks like the sqlalchemy iterator just converts it to a list and exposes them as a generator # If we had access to the cursor, we could ask for rowcount before we iterate over the results query_results = query.all() # Get the total and page calculations in case we need to go "backwards" in the query total = total_query.scalar() pages, remainder = divmod(total, count) last_page = pages + (1 if remainder > 0 else 0) if offset == 0 or len(query_results) > 0: # We have some valid data (i.e. a valid offset was requested) # Break out of the loop and render them break # We got a request for a page that is out of bounds, go back to the last page and return that offset = (last_page - 1) * count iquery = iter(query_results) last_result = None r_visitor = self.read_visitor(session=self.db.session, with_extensions=with_extensions) results = [] if has_extra: for r in itertools.islice(iquery, count): last_result = r[0] d = r_visitor.visit_model(r[0], field_names=field_names, summary=summary, exclude=exclude_fields, include=include_fields) extra = r._asdict() v = extra.pop(r.keys()[0]) assert v is r[0], "We were assuming the result object is an ordered dict" d.update(extra) results.append(d) else: for r in itertools.islice(iquery, count): last_result = r d = r_visitor.visit_model(r, field_names=field_names, summary=summary, exclude=exclude_fields, include=include_fields) results.append(d) next_result = next(iquery, None) if next_result is not None: next_token_payload = dict( identity=identity, last_id=next_result.uid if isinstance(next_result, UidMixin) else None, offset=offset + count, ) else: next_token_payload = dict( identity=identity, last_id=last_result.uid if isinstance(last_result, UidMixin) else None, offset=(offset + count) if last_result else offset, ) next_token = serializer.dumps(next_token_payload, header_fields={'v': 1}).decode('ascii') output = dict( results=results, pagination=dict( nextToken=next_token, count=len(results), offset=offset + 1, total=total, more=bool(next_result is not None), page=offset//count + 1, ), ) return output, 200
def generate_password_hash(self, password): s = JSONWebSignatureSerializer(Config.SECRET_KEY) self.password_hash = s.dumps(password) return self.password_hash
def sign(self, value): if isinstance(value, bytes): value = value.decode("utf-8") s = JSONWebSignatureSerializer(self.secret_key) return s.dumps(value)
def generate_email_change_token(self, new_email, expiration=3600): s = JSONWebSignatureSerializer(current_app.config['SECRET_KEY']) return s.dumps({ 'change_email': self.id, 'new_email': new_email }).decode('utf-8')
from itsdangerous import JSONWebSignatureSerializer, SignatureExpired, BadSignature import datetime from datetime import timedelta import time from datetime import datetime private_key = "Highway is so far away" encrypt = JSONWebSignatureSerializer(private_key) import json from datetime import datetime def encryptToken(username, password): result = { 'username': username, 'password': password, 'creation-time': str(datetime.now()) } # jsonResult = json.dumps(result) return encrypt.dumps(result) def decryptToken(token): #sig checks if the data is valid and not unsafe payload = encrypt.loads(token) create = payload.get('creation-time') if datetime.now() > datetime.strptime( create, "%Y-%m-%d %H:%M:%S.%f") + timedelta(minutes=30): raise SignatureExpired("Token created more than 10 seconds ago") return payload
def generate_token(self): s = JSONWebSignatureSerializer(current_app.config['SECRET_KEY']) return s.dumps({'id': self.id})
from itsdangerous.url_safe import URLSafeSerializer s = URLSafeSerializer("secret-key") ret = s.dumps([1, 2, 3, 4]) print(ret) # 输出:WzEsMiwzLDRd.wSPHqC0gR7VUqivlSukJ0IeTDgo raw_list = s.loads("WzEsMiwzLDRd.wSPHqC0gR7VUqivlSukJ0IeTDgo") print(raw_list) # 输出:[1, 2, 3, 4] 5. JSON Web Signature (JWS) JSONWebSignatureSerializer 类 和 URLSafeSerializer 类似,但是 这个类 生成的 签名和 JWS 是一样的,包含了头部。 基本使用例子: from itsdangerous import JSONWebSignatureSerializer s = JSONWebSignatureSerializer("secret-key") ret = s.dumps({"user_id":1}, header_fields={"v": 1}) print(ret) # b"eyJ2IjoxLCJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxfQ.1dOfAWWvjZJBxF96HlUMlPqc6tnoLPxWAq6k_MpfycTRiQZ1IDdK9XmBahhV5i4JsjnSTZW-sWfW4jsYpI-Rvw" raw_data = s.loads(b"eyJ2IjoxLCJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxfQ.1dOfAWWvjZJBxF96HlUMlPqc6tnoLPxWAq6k_MpfycTRiQZ1IDdK9XmBahhV5i4JsjnSTZW-sWfW4jsYpI-Rvw",return_header=True) print(raw_data) #输出:({'user_id': 1}, {'v': 1, 'alg': 'HS512'}) 详解: 1) dumps 方法中 header_fields参数用来指定 自定义 JWS头部 2)loads 方法中 return_header 参数 用来指定,返回的 反序列化数据 是否包含 JWS头部。 如果包含,载荷 和头部 以元组 形式返回 3)TimedJSONWebSignatureSerializer 默认过期时间 1小时 文档:https://itsdangerous.palletsprojects.com/en/1.1.x/jws/
def init_app(self, app): """ Do setup that requires a Flask app. :param app: The application to initialize. :type app: Flask """ secrets = self.load_secrets(app) self.client_secrets = list(secrets.values())[0] secrets_cache = DummySecretsCache(secrets) # Set some default configuration options app.config.setdefault('OIDC_SCOPES', ['openid', 'email']) app.config.setdefault('OIDC_GOOGLE_APPS_DOMAIN', None) app.config.setdefault('OIDC_ID_TOKEN_COOKIE_NAME', 'oidc_id_token') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_PATH', '/') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_TTL', 7 * 86400) # 7 days # should ONLY be turned off for local debugging app.config.setdefault('OIDC_COOKIE_SECURE', True) app.config.setdefault( 'OIDC_VALID_ISSUERS', (self.client_secrets.get('issuer') or GOOGLE_ISSUERS)) app.config.setdefault('OIDC_CLOCK_SKEW', 60) # 1 minute app.config.setdefault('OIDC_REQUIRE_VERIFIED_EMAIL', False) app.config.setdefault('OIDC_OPENID_REALM', None) app.config.setdefault('OIDC_USER_INFO_ENABLED', True) app.config.setdefault('OIDC_CALLBACK_ROUTE', '/oidc_callback') app.config.setdefault('OVERWRITE_REDIRECT_URI', False) app.config.setdefault("OIDC_EXTRA_REQUEST_AUTH_PARAMS", {}) # Configuration for resource servers app.config.setdefault('OIDC_RESOURCE_SERVER_ONLY', False) app.config.setdefault('OIDC_RESOURCE_CHECK_AUD', False) # We use client_secret_post, because that's what the Google # oauth2client library defaults to app.config.setdefault('OIDC_INTROSPECTION_AUTH_METHOD', 'client_secret_post') app.config.setdefault('OIDC_TOKEN_TYPE_HINT', 'access_token') if not 'openid' in app.config['OIDC_SCOPES']: raise ValueError('The value "openid" must be in the OIDC_SCOPES') # register callback route and cookie-setting decorator if not app.config['OIDC_RESOURCE_SERVER_ONLY']: app.route(app.config['OIDC_CALLBACK_ROUTE'])(self._oidc_callback) app.before_request(self._before_request) app.after_request(self._after_request) # Initialize oauth2client self.flow = flow_from_clientsecrets(app.config['OIDC_CLIENT_SECRETS'], scope=app.config['OIDC_SCOPES'], cache=secrets_cache) assert isinstance(self.flow, OAuth2WebServerFlow) # create signers using the Flask secret key self.extra_data_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-extra-data') self.cookie_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-cookie') try: self.credentials_store = app.config['OIDC_CREDENTIALS_STORE'] except KeyError: pass
def generate_auth_token(email): s = JSONWebSignatureSerializer(app.config['SECRET_KEY']) return s.dumps({'email': email})
def init_app(self, app): """ Do setup that requires a Flask app. :param app: The application to initialize. :type app: Flask """ secrets = self.load_secrets(app) self.client_secrets = list(secrets.values())[0] secrets_cache = DummySecretsCache(secrets) # Set some default configuration options app.config.setdefault("OIDC_SCOPES", ["openid", "email"]) app.config.setdefault("OIDC_GOOGLE_APPS_DOMAIN", None) app.config.setdefault("OIDC_ID_TOKEN_COOKIE_NAME", "oidc_id_token") app.config.setdefault("OIDC_ID_TOKEN_COOKIE_PATH", "/") app.config.setdefault("OIDC_ID_TOKEN_COOKIE_TTL", 7 * 86400) # 7 days # should ONLY be turned off for local debugging app.config.setdefault("OIDC_COOKIE_SECURE", True) app.config.setdefault( "OIDC_VALID_ISSUERS", (self.client_secrets.get("issuer") or GOOGLE_ISSUERS) ) app.config.setdefault("OIDC_CLOCK_SKEW", 60) # 1 minute app.config.setdefault("OIDC_REQUIRE_VERIFIED_EMAIL", False) app.config.setdefault("OIDC_OPENID_REALM", None) app.config.setdefault("OIDC_USER_INFO_ENABLED", True) app.config.setdefault("OIDC_CALLBACK_ROUTE", "/oidc_callback") app.config.setdefault("OVERWRITE_REDIRECT_URI", False) app.config.setdefault("OIDC_EXTRA_REQUEST_AUTH_PARAMS", {}) app.config.setdefault("OIDC_EXTRA_REQUEST_HEADERS", {}) # Configuration for resource servers app.config.setdefault("OIDC_RESOURCE_SERVER_ONLY", False) app.config.setdefault("OIDC_RESOURCE_CHECK_AUD", False) # We use client_secret_post, because that's what the Google # oauth2client library defaults to app.config.setdefault("OIDC_INTROSPECTION_AUTH_METHOD", "client_secret_post") app.config.setdefault("OIDC_TOKEN_TYPE_HINT", "access_token") if not "openid" in app.config["OIDC_SCOPES"]: raise ValueError('The value "openid" must be in the OIDC_SCOPES') # register callback route and cookie-setting decorator if not app.config["OIDC_RESOURCE_SERVER_ONLY"]: app.route(app.config["OIDC_CALLBACK_ROUTE"])(self._oidc_callback) app.before_request(self._before_request) app.after_request(self._after_request) # Initialize oauth2client self.flow = flow_from_clientsecrets( app.config["OIDC_CLIENT_SECRETS"], scope=app.config["OIDC_SCOPES"], cache=secrets_cache, ) assert isinstance(self.flow, OAuth2WebServerFlow) # TODO use configurable salt string instead of hardcoded value to improve security # create signers using the Flask secret key self.extra_data_serializer = JSONWebSignatureSerializer( app.config["SECRET_KEY"], salt="flask-oidc-extra-data" ) self.cookie_serializer = JSONWebSignatureSerializer( app.config["SECRET_KEY"], salt="flask-oidc-cookie" ) try: self.credentials_store = app.config["OIDC_CREDENTIALS_STORE"] except KeyError: pass
def unsign(self, value): s = JSONWebSignatureSerializer(self.secret_key) try: return s.loads(value) except BadSignature: return {}