Python jwt.encode() Examples
The following are 30
code examples of jwt.encode().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
jwt
, or try the search function
.
Example #1
Source File: utils.py From django-oauth-toolkit-jwt with MIT License | 7 votes |
def encode_jwt(payload, headers=None): """ :type payload: dict :type headers: dict, None :rtype: str """ # RS256 in default, because hardcoded legacy algorithm = getattr(settings, 'JWT_ENC_ALGORITHM', 'RS256') private_key_name = 'JWT_PRIVATE_KEY_{}'.format(payload['iss'].upper()) private_key = getattr(settings, private_key_name, None) if not private_key: raise ImproperlyConfigured('Missing setting {}'.format( private_key_name)) encoded = jwt.encode(payload, private_key, algorithm=algorithm, headers=headers) return encoded.decode("utf-8")
Example #2
Source File: user.py From SempoBlockchain with GNU General Public License v3.0 | 7 votes |
def encode_auth_token(self): """ Generates the Auth Token :return: string """ try: payload = { 'exp': datetime.datetime.utcnow() + datetime.timedelta(days=7, seconds=0), 'iat': datetime.datetime.utcnow(), 'id': self.id, 'roles': self.roles } return jwt.encode( payload, current_app.config['SECRET_KEY'], algorithm='HS256' ) except Exception as e: return e
Example #3
Source File: env.py From typot with Apache License 2.0 | 6 votes |
def make_auth_header(installation_id): utcnow = datetime.utcnow() + timedelta(seconds=-5) duration = timedelta(seconds=30) payload = { "iat": utcnow, "exp": utcnow + duration, "iss": 2510 } pem = get_private_pem() encoded = jwt.encode(payload, pem, "RS256") headers = { "Authorization": "Bearer " + encoded.decode("utf-8"), "Accept": "application/vnd.github.machine-man-preview+json" } auth_url = "https://api.github.com/installations/{}/access_tokens".format(installation_id) r = requests.post(auth_url, headers=headers) if not r.ok: print(r.json()["message"]) r.raise_for_status() token = r.json()["token"] return { "Authorization": "token {}".format(token) }
Example #4
Source File: MainClass.py From gist-alfred with MIT License | 6 votes |
def create_jwt(self, 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 expiration: int :return: """ now = int(time.time()) payload = { "iat": now, "exp": now + expiration, "iss": self.integration_id } encrypted = jwt.encode( payload, key=self.private_key, algorithm="RS256" ) if atLeastPython3: encrypted = encrypted.decode('utf-8') return encrypted
Example #5
Source File: user.py From SempoBlockchain with GNU General Public License v3.0 | 6 votes |
def encode_TFA_token(self, valid_days=1): """ Generates the Auth Token for TFA :return: string """ try: payload = { 'exp': datetime.datetime.utcnow() + datetime.timedelta(days=valid_days, seconds=30), 'iat': datetime.datetime.utcnow(), 'id': self.id } return jwt.encode( payload, current_app.config['SECRET_KEY'], algorithm='HS256' ) except Exception as e: return e
Example #6
Source File: token_manager.py From Paradrop with Apache License 2.0 | 6 votes |
def issue(self, subject, expires=2592000, **claims): """ Issue a signed token. The subject is mandatory and sets the JWT "sub" claim. The expiration time can be None (no expiration) or a time in seconds from the issue time after which the token will expire. The default is 30 days (2592000 seconds). """ data = claims data['iat'] = int(time.time()) data['iss'] = nexus.core.info.pdid data['sub'] = subject if expires is not None: data['exp'] = int(time.time()) + expires return jwt.encode(data, self.secret, algorithm='HS256')
Example #7
Source File: tokens.py From flask-jwt-extended with MIT License | 6 votes |
def _encode_jwt(additional_token_data, expires_delta, secret, algorithm, json_encoder=None, headers=None): uid = _create_csrf_token() now = datetime.datetime.utcnow() token_data = { 'iat': now, 'nbf': now, 'jti': uid, } # If expires_delta is False, the JWT should never expire # and the 'exp' claim is not set. if expires_delta: token_data['exp'] = now + expires_delta token_data.update(additional_token_data) encoded_token = jwt.encode(token_data, secret, algorithm, json_encoder=json_encoder, headers=headers).decode('utf-8') return encoded_token
Example #8
Source File: api_client.py From docusign-python-client with MIT License | 6 votes |
def generate_access_token(self, client_id, client_secret, code): """ GenerateAccessToken will exchange the authorization code for an access token and refresh tokens. :param client_id: DocuSign OAuth Client Id(AKA Integrator Key) :param client_secret: The secret key you generated when you set up the integration in DocuSign Admin console. :param code: The authorization code :return: OAuthToken object """ if not client_id or not client_secret or not code: raise ArgumentException url = "https://{0}/oauth/token".format(self.oauth_host_name) integrator_and_secret_key = b"Basic " + base64.b64encode(str.encode("{}:{}".format(client_id, client_secret))) headers = { "Authorization": integrator_and_secret_key.decode("utf-8"), "Content-Type": "application/x-www-form-urlencoded", } post_params = self.sanitize_for_serialization({ "grant_type": "authorization_code", "code": code }) response = self.rest_client.POST(url, headers=headers, post_params=post_params) return self.deserialize(response=response, response_type=OAuthToken)
Example #9
Source File: auth.py From auth-server-sample with Apache License 2.0 | 6 votes |
def generate_authorization_code(client_id, redirect_url): #f = Fernet(KEY) authorization_code = f.encrypt(json.dumps({ "client_id": client_id, "redirect_url": redirect_url, }).encode()) authorization_code = base64.b64encode(authorization_code, b'-_').decode().replace('=', '') expiration_date = time.time() + CODE_LIFE_SPAN authorization_codes[authorization_code] = { "client_id": client_id, "redirect_url": redirect_url, "exp": expiration_date } return authorization_code
Example #10
Source File: utils.py From full-stack-fastapi-couchbase with MIT License | 6 votes |
def generate_password_reset_token(username): delta = timedelta(hours=config.EMAIL_RESET_TOKEN_EXPIRE_HOURS) now = datetime.utcnow() expires = now + delta exp = expires.timestamp() encoded_jwt = jwt.encode( { "exp": exp, "nbf": now, "sub": password_reset_jwt_subject, "username": username, }, config.SECRET_KEY, algorithm="HS256", ) return encoded_jwt
Example #11
Source File: test_api_lib_utils.py From privacyidea with GNU Affero General Public License v3.0 | 6 votes |
def test_04_check_jwt_username_in_audit(self): # Here we check, if the username from the trusted JWT appears in the audit log. # This means that the username is read in the correct way from the JWT and # also used in the correct way for policy handling. with open("tests/testdata/jwt_sign.key", "r") as f: key = f.read() auth_token = jwt.encode(payload={"role": "user", "username": "userA", "realm": "realm1", "resolver": "resolverX"}, key=key, algorithm="RS256") # The authenticated but non-existing user tries for fetch his tokens with self.app.test_request_context('/token/', method='GET', headers={"Authorization": auth_token}): res = self.app.full_dispatch_request() self.assertTrue(res.status_code == 400, res) # We see the user from the trusted JWT in the audit log. ae = self.find_most_recent_audit_entry(action="GET /token/") self.assertEqual(ae.get("user"), u"userA")
Example #12
Source File: ddb.py From avrae with GNU General Public License v3.0 | 6 votes |
def _jwt_for_user(user_id: int): """ Gets the HS256-encoded JWT for a Discord user ID. :param int user_id: The Discord user ID. :returns str: The JWT. """ now = int(time.time()) jwt_body = { "external_user_id": str(user_id), "iat": now, "exp": now + EXPIRY_SECONDS, "aud": AUDIENCE, "iss": ISSUER } return jwt.encode(jwt_body, MY_SECRET, algorithm='HS256').decode() # return as a str, not bytes
Example #13
Source File: githubhandler.py From bioconda-utils with MIT License | 6 votes |
def get_app_jwt(self) -> str: """Returns JWT authenticating as this app""" now = int(time.time()) expires, token = self._jwt if not expires or expires < now + 60: expires = now + self.JWT_RENEW_PERIOD payload = { 'iat': now, 'exp': expires, 'iss': self.app_id, } token_utf8 = jwt.encode(payload, self.app_key, algorithm="RS256") token = token_utf8.decode("utf-8") self._jwt = (expires, token) msg = "Created new" else: msg = "Reusing" logger.debug("%s JWT valid for %i minutes", msg, (expires - now)/60) return token
Example #14
Source File: tutorial005.py From fastapi with MIT License | 5 votes |
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None): to_encode = data.copy() if expires_delta: expire = datetime.utcnow() + expires_delta else: expire = datetime.utcnow() + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt
Example #15
Source File: connection.py From aioapns with Apache License 2.0 | 5 votes |
def get_header(self): now = time.time() if not self.__header or self.__issued_at < now - self.TOKEN_TTL: self.__issued_at = int(now) token = jwt.encode( payload={'iss': self.team_id, 'iat': self.__issued_at}, key=self.key, algorithm='ES256', headers={'kid': self.key_id}, ).decode('ascii') self.__header = f"bearer {token}" return self.__header
Example #16
Source File: tutorial004.py From fastapi with MIT License | 5 votes |
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None): to_encode = data.copy() if expires_delta: expire = datetime.utcnow() + expires_delta else: expire = datetime.utcnow() + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt
Example #17
Source File: models.py From AUCR with GNU General Public License v3.0 | 5 votes |
def get_reset_password_token(self, expires_in=600): """Return user reset password token.""" return jwt.encode({'reset_password': self.id, 'exp': time() + expires_in}, current_app.config['SECRET_KEY'], algorithm='HS256').decode('utf-8')
Example #18
Source File: models.py From kobo-predict with BSD 2-Clause "Simplified" License | 5 votes |
def clean(self): if not hasattr(self, 'auth_user') or not self.auth_user: User = get_user_model() user = User.objects.create_user( username=generate_random_username() ) self.auth_user = user if not hasattr(self, 'token') or not self.token: payload = {'userId': self.auth_user.id} self.token = jwt.encode( payload, settings.SECRET_KEY, algorithm='HS256', )
Example #19
Source File: quoine.py From cryptojp with MIT License | 5 votes |
def __init__(self, apikey, secretkey): def httpGet(url, resource, params, apikey, sign): payload = {'nonce': str(int("{:.6f}".format( time.time()).replace('.', ''))), 'path': resource, 'token_id': self._apikey} headers = { 'Accept': 'application/json', 'X-Quoine-API-Version': '2', "X-Quoine-Auth": apikey, "Sign": jwt.encode(payload, self._secretkey, 'HS256'), } return self.session.get('https://' + url + resource, headers=headers, data=params).json() def httpPost(url, resource, params, apikey): payload = {'nonce': str(int("{:.6f}".format( time.time()).replace('.', ''))), 'path': resource, 'token_id': self._apikey} headers = { 'Accept': 'application/json', 'X-Quoine-API-Version': '2', "X-Quoine-Auth": apikey, "Sign": jwt.encode(payload, self._secretkey, 'HS256'), } return self.session.post('https://' + url + resource, headers=headers, data=params).json() def httpPut(url, resource, params, apikey): payload = {'nonce': str(int("{:.6f}".format( time.time()).replace('.', ''))), 'path': resource, 'token_id': self._apikey} headers = { 'Accept': 'application/json', 'X-Quoine-API-Version': '2', "X-Quoine-Auth": apikey, "Sign": jwt.encode(payload, self._secretkey, 'HS256'), } return self.session.put('https://' + url + resource, headers=headers, data=params).json() super(Quoine, self).__init__(apikey, secretkey) self.session = requests.session() self.httpPost = httpPost self.httpGet = httpGet self.httpPut = httpPut
Example #20
Source File: auth.py From dcos-deploy with Apache License 2.0 | 5 votes |
def _read_config_from_service_account(): global _base_url, _auth credentials = os.environ.get(ENV_DCOS_SERVICE_ACCOUNT_CREDENTIAL) if not credentials: return False credentials = json.loads(credentials) _base_url = os.environ.get(ENV_BASE_URL) if not credentials or not _base_url: return False uid = credentials["uid"] private_key = credentials["private_key"] login_endpoint = credentials['login_endpoint'] now = int(time.time()) payload = { 'uid': uid, 'exp': now + 60, # expiry time of the auth request params } token = jwt.encode(payload, private_key, 'RS256') data = { 'uid': uid, 'token': token.decode('ascii'), 'exp': now + 30*60, # expiry time for the token } r = requests.post(login_endpoint, json=data, timeout=(3.05, 46), verify=False) r.raise_for_status() _auth = StaticTokenAuth(r.cookies['dcos-acs-auth-cookie']) return True
Example #21
Source File: user.py From SempoBlockchain with GNU General Public License v3.0 | 5 votes |
def salt_hash_secret(password): f = Fernet(config.PASSWORD_PEPPER) return f.encrypt(bcrypt.hashpw(password.encode(), bcrypt.gensalt())).decode()
Example #22
Source File: utils.py From flask-jwt-extended with MIT License | 5 votes |
def encode_token(app, token_data, headers=None): with app.test_request_context(): token = jwt.encode( token_data, config.decode_key, algorithm=config.algorithm, json_encoder=config.json_encoder, headers=headers ) return token.decode('utf-8')
Example #23
Source File: tokens.py From flask-jwt-extended with MIT License | 5 votes |
def encode_refresh_token(identity, secret, algorithm, expires_delta, user_claims, csrf, identity_claim_key, user_claims_key, json_encoder=None, headers=None): """ Creates a new encoded (utf-8) refresh token. :param identity: Some identifier used to identify the owner of this token :param secret: Secret key to encode the JWT with :param algorithm: Which algorithm to use for the toek :param expires_delta: How far in the future this token should expire (set to False to disable expiration) :type expires_delta: datetime.timedelta or False :param user_claims: Custom claims to include in this token. This data must be json serializable :param csrf: Whether to include a csrf double submit claim in this token (boolean) :param identity_claim_key: Which key should be used to store the identity :param user_claims_key: Which key should be used to store the user claims :param headers: valid dict for specifying additional headers in JWT header section :return: Encoded refresh token """ token_data = { identity_claim_key: identity, 'type': 'refresh', } # Don't add extra data to the token if user_claims is empty. if user_claims: token_data[user_claims_key] = user_claims if csrf: token_data['csrf'] = _create_csrf_token() return _encode_jwt(token_data, expires_delta, secret, algorithm, json_encoder=json_encoder, headers=headers)
Example #24
Source File: api_client.py From docusign-python-client with MIT License | 5 votes |
def request_jwt_application_token(self, client_id, oauth_host_name, private_key_bytes, expires_in, scopes=(OAuth.SCOPE_SIGNATURE,)): """ Request JWT Application Token :param client_id: DocuSign OAuth Client Id(AKA Integrator Key) :param oauth_host_name: DocuSign OAuth host name :param private_key_bytes: the byte contents of the RSA private key :param expires_in: number of seconds remaining before the JWT assertion is considered as invalid :param scopes: Optional. The list of requested scopes may include (but not limited to) You can also pass any advanced scope. :return: OAuthToken object """ if not private_key_bytes: raise ArgumentException("Private key not supplied or is invalid!") if not oauth_host_name: raise ArgumentException("oAuthBasePath cannot be empty") now = math.floor(time()) later = now + (expires_in * 1) claim = {"iss": client_id, "aud": oauth_host_name, "iat": now, "exp": later, "scope": " ".join(scopes)} token = jwt.encode(payload=claim, key=private_key_bytes, algorithm='RS256') response = self.request("POST", "https://" + oauth_host_name + "/oauth/token", headers=self.sanitize_for_serialization( {"Content-Type": "application/x-www-form-urlencoded"}), post_params=self.sanitize_for_serialization( {"assertion": token, "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer"})) response_data = json.loads(response.data) if 'token_type' in response_data and 'access_token' in response_data: self.set_default_header("Authorization", response_data['token_type'] + " " + response_data['access_token']) else: ApiException(status=response.status, reason="Error while requesting server, received a non successful HTTP code {}" " with response Body: {}".format(response.status, response.data) ) return self.deserialize(response=response, response_type=OAuthToken)
Example #25
Source File: views.py From certificate-generator-server-archive with GNU General Public License v3.0 | 5 votes |
def create(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) try: if serializer.is_valid(raise_exception=True): user = serializer.create(request.data) jwt_token = {'token': jwt.encode( serializer.data, config('SECRET_KEY'))} return Response(jwt_token, status=status.HTTP_201_CREATED) except IntegrityError: serializer.error_messages = { 'Error': 'Organization with that username already exists!'} return Response(serializer.error_messages, status=status.HTTP_400_BAD_REQUEST)
Example #26
Source File: util.py From insightconnect-plugins with MIT License | 5 votes |
def create_jwt_token(application_id: str, api_key: str, http_method: str, raw_url: str, header: str, request_body: str, algorithm='HS256') -> str: """Generate a JWT token for an Apex HTTP request. Specific to a url destination and payload""" issue_time = time.time() payload = {'appid': application_id, 'iat': issue_time, 'version': 'V1', 'checksum': create_base64_checksum(http_method, raw_url, header, request_body)} token = jwt.encode(payload, api_key, algorithm).decode('utf-8') return token
Example #27
Source File: util.py From insightconnect-plugins with MIT License | 5 votes |
def create_base64_checksum(http_method: str, raw_url: str, raw_header: str, request_body: str) -> str: """Create a base64 encoded hash string for an Apex JWT token""" string_to_hash = http_method.upper() + '|' + raw_url.lower() + '|' + raw_header + '|' + request_body base64_hash_string = base64.b64encode(hashlib.sha256(str.encode(string_to_hash)).digest()).decode('utf-8') return base64_hash_string
Example #28
Source File: jwt.py From full-stack-fastapi-couchbase with MIT License | 5 votes |
def create_access_token(*, data: dict, expires_delta: timedelta = None): to_encode = data.copy() if expires_delta: expire = datetime.utcnow() + expires_delta else: expire = datetime.utcnow() + timedelta(minutes=15) to_encode.update({"exp": expire, "sub": access_token_jwt_subject}) encoded_jwt = jwt.encode(to_encode, config.SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt
Example #29
Source File: github.py From release-bot with GNU General Public License v3.0 | 5 votes |
def generate_token(self): # Generate the JWT payload = { # issued at time 'iat': int(time.time()), # JWT expiration time (10 minute maximum) 'exp': int(time.time()) + self.expiration, # GitHub App's identifier 'iss': self.iss } tok = jwt.encode(payload, self.key, algorithm='RS256') return tok.decode('utf-8')
Example #30
Source File: service.py From everyclass-server with Mozilla Public License 2.0 | 5 votes |
def issue_token(user_identifier: str) -> str: """签发指定用户名的JWT token""" from everyclass.server.utils.config import get_config config = get_config() payload = {"username": user_identifier} token = jwt.encode(payload, config.JWT_PRIVATE_KEY, algorithm='RS256') return token.decode('utf8')