Python jose.jwt.encode() Examples
The following are 30
code examples of jose.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
jose.jwt
, or try the search function
.
Example #1
Source File: test_jwt.py From python-jose with MIT License | 6 votes |
def test_nbf_skip(self, key): nbf = datetime.utcnow() + timedelta(seconds=5) claims = { 'nbf': nbf } token = jwt.encode(claims, key) with pytest.raises(JWTError): jwt.decode(token, key) options = { 'verify_nbf': False } jwt.decode(token, key, options=options)
Example #2
Source File: test_tokens.py From django-rest-framework-simplejwt with MIT License | 6 votes |
def test_init_bad_sig_token_given_no_verify(self): # Test backend rejects encoded token (expired or bad signature) payload = {'foo': 'bar'} payload['exp'] = aware_utcnow() + timedelta(days=1) token_1 = jwt.encode(payload, api_settings.SIGNING_KEY, algorithm='HS256') payload['foo'] = 'baz' token_2 = jwt.encode(payload, api_settings.SIGNING_KEY, algorithm='HS256') token_2_payload = token_2.rsplit('.', 1)[0] token_1_sig = token_1.rsplit('.', 1)[-1] invalid_token = token_2_payload + '.' + token_1_sig t = MyToken(invalid_token, verify=False) self.assertEqual( t.payload, payload, )
Example #3
Source File: test_tokens.py From django-rest-framework-simplejwt with MIT License | 6 votes |
def test_str(self): token = MyToken() token.set_exp( from_time=make_utc(datetime(year=2000, month=1, day=1)), lifetime=timedelta(seconds=0), ) # Delete all but one claim. We want our lives to be easy and for there # to only be a couple of possible encodings. We're only testing that a # payload is successfully encoded here, not that it has specific # content. del token[api_settings.TOKEN_TYPE_CLAIM] del token['jti'] # Should encode the given token encoded_token = str(token) # Token could be one of two depending on header dict ordering self.assertIn( encoded_token, ( 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjk0NjY4NDgwMH0.VKoOnMgmETawjDZwxrQaHG0xHdo6xBodFy6FXJzTVxs', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjk0NjY4NDgwMH0.iqxxOHV63sjeqNR1GDxX3LPvMymfVB76sOIDqTbjAgk', ), )
Example #4
Source File: test_jwt.py From python-jose with MIT License | 6 votes |
def test_no_alg(self, claims, key): token = jwt.encode(claims, key, algorithm='HS384') b64header, b64payload, b64signature = token.split('.') header_json = base64.urlsafe_b64decode(b64header.encode('utf-8')) header = json.loads(header_json.decode('utf-8')) del header['alg'] bad_header_json_bytes = json.dumps(header).encode('utf-8') bad_b64header_bytes = base64.urlsafe_b64encode(bad_header_json_bytes) bad_b64header_bytes_short = bad_b64header_bytes.replace(b'=', b'') bad_b64header = bad_b64header_bytes.decode('utf-8') bad_token = '.'.join([bad_b64header, b64payload, b64signature]) with pytest.raises(JWTError): jwt.decode( token=bad_token, key=key, algorithms=[])
Example #5
Source File: api.py From Avalon-Management-System with GNU General Public License v3.0 | 6 votes |
def login(): username = request.json['username'] password = request.json['password'] hash_password = hashlib.sha256(password.encode()).hexdigest() result = g.database.run( 'select', 'user', ['password'], 'username = %s', [username] ) if len(result) == 0 or hash_password != result[0][0]: return '{"auth": false}' claims = { 'exp': int(time.time()) + 3600, 'name': username, } token = jwt.encode(claims, jwt_password, algorithm='HS256') return ams_dumps({"auth": True, "token": token})
Example #6
Source File: jwt.py From dvhb-hybrid with MIT License | 6 votes |
def generate(self, *args, **kwargs): cfg = self.config if not args: payload = {} elif not isinstance(args[0], Mapping): raise ValueError(args) else: payload = dict(args[0]) payload.update(kwargs) now = datetime.utcnow() payload.setdefault('iat', now) exp = payload.get('exp') if not exp: payload['exp'] = now + timedelta(seconds=cfg.get_duration('life')) elif isinstance(exp, timedelta): payload['exp'] += now return jwt.encode(payload, cfg.secret, algorithm=cfg.algorithms[0])
Example #7
Source File: test_jwt.py From python-jose with MIT License | 6 votes |
def test_exp_skip(self, key): exp = datetime.utcnow() - timedelta(seconds=5) claims = { 'exp': exp } token = jwt.encode(claims, key) with pytest.raises(JWTError): jwt.decode(token, key) options = { 'verify_exp': False } jwt.decode(token, key, options=options)
Example #8
Source File: rsa_auth.py From symphony-api-client-python with MIT License | 6 votes |
def create_jwt(self): """ Create a jwt token with payload dictionary. Encode with RSA private key using RS512 algorithm :return: A jwt token valid for < 290 seconds """ logging.debug('RSA_auth/getJWT() function started') with open(self.config.data['botRSAPath'], 'r') as f: content = f.readlines() private_key = ''.join(content) expiration_date = int(datetime.datetime.now(datetime.timezone.utc) .timestamp() + (5*58)) payload = { 'sub': self.config.data['botUsername'], 'exp': expiration_date } encoded = jwt.encode(payload, private_key, algorithm='RS512') f.close() return encoded
Example #9
Source File: test_jwt.py From python-jose with MIT License | 6 votes |
def test_encode(self, claims, key): expected = ( ( 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9' '.eyJhIjoiYiJ9' '.xNtk2S0CNbCBZX_f67pFgGRugaP1xi2ICfet3nwOSxw' ), ( 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9' '.eyJhIjoiYiJ9' '.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8' ) ) encoded = jwt.encode(claims, key) assert encoded in expected
Example #10
Source File: models.py From papers with MIT License | 6 votes |
def validate(cls, email, password): docs = list(r.table(cls._table).filter({'email': email}).run(conn)) if not len(docs): raise ValidationError("Could not find the e-mail address you specified") _hash = docs[0]['password'] if cls.verify_password(password, _hash): try: token = jwt.encode({'id': docs[0]['id']}, current_app.config['SECRET_KEY'], algorithm='HS256') return token except JWTError: raise ValidationError("There was a problem while trying to create a JWT token.") else: raise ValidationError("The password you inputed was incorrect.")
Example #11
Source File: test_jwt.py From python-jose with MIT License | 5 votes |
def test_sub_incorrect(self, key): sub = 'subject' claims = { 'sub': sub } token = jwt.encode(claims, key) with pytest.raises(JWTError): jwt.decode(token, key, subject='another')
Example #12
Source File: test_jwt.py From python-jose with MIT License | 5 votes |
def test_at_hash_missing_access_token(self, claims, key): token = jwt.encode(claims, key, access_token='<ACCESS_TOKEN>') with pytest.raises(JWTError): jwt.decode(token, key)
Example #13
Source File: test_jwt.py From python-jose with MIT License | 5 votes |
def test_sub_correct(self, key): sub = 'subject' claims = { 'sub': sub } token = jwt.encode(claims, key) jwt.decode(token, key, subject=sub)
Example #14
Source File: test_jwt.py From python-jose with MIT License | 5 votes |
def test_sub_invalid(self, key): sub = 1 claims = { 'sub': sub } token = jwt.encode(claims, key) with pytest.raises(JWTError): jwt.decode(token, key)
Example #15
Source File: test_jwt.py From python-jose with MIT License | 5 votes |
def test_sub_string(self, key): sub = 'subject' claims = { 'sub': sub } token = jwt.encode(claims, key) jwt.decode(token, key)
Example #16
Source File: test_jwt.py From python-jose with MIT License | 5 votes |
def test_iss_invalid(self, key): iss = 'issuer' claims = { 'iss': iss } token = jwt.encode(claims, key) with pytest.raises(JWTError): jwt.decode(token, key, issuer='another')
Example #17
Source File: test_jwt.py From python-jose with MIT License | 5 votes |
def test_iss_list(self, key): iss = 'issuer' claims = { 'iss': iss } token = jwt.encode(claims, key) jwt.decode(token, key, issuer=['https://issuer', 'issuer'])
Example #18
Source File: test_jwt.py From python-jose with MIT License | 5 votes |
def test_iss_string(self, key): iss = 'issuer' claims = { 'iss': iss } token = jwt.encode(claims, key) jwt.decode(token, key, issuer=iss)
Example #19
Source File: test_jwt.py From python-jose with MIT License | 5 votes |
def test_jti_invalid(self, key): jti = 1 claims = { 'jti': jti } token = jwt.encode(claims, key) with pytest.raises(JWTError): jwt.decode(token, key)
Example #20
Source File: test_jwt.py From python-jose with MIT License | 5 votes |
def test_at_hash(self, claims, key): access_token = '<ACCESS_TOKEN>' token = jwt.encode(claims, key, access_token=access_token) payload = jwt.decode(token, key, access_token=access_token) assert 'at_hash' in payload
Example #21
Source File: test_jwt.py From python-jose with MIT License | 5 votes |
def test_at_hash_invalid(self, claims, key): token = jwt.encode(claims, key, access_token='<ACCESS_TOKEN>') with pytest.raises(JWTError): jwt.decode(token, key, access_token='<OTHER_TOKEN>')
Example #22
Source File: test_jwt.py From python-jose with MIT License | 5 votes |
def test_aud_list_is_strings(self, key): aud = 'audience' claims = { 'aud': [aud, 1] } token = jwt.encode(claims, key) with pytest.raises(JWTError): jwt.decode(token, key, audience=aud)
Example #23
Source File: test_jwt.py From python-jose with MIT License | 5 votes |
def test_at_hash_missing_claim(self, claims, key): token = jwt.encode(claims, key) payload = jwt.decode(token, key, access_token='<ACCESS_TOKEN>') assert 'at_hash' not in payload
Example #24
Source File: test_jwt.py From python-jose with MIT License | 5 votes |
def test_unverified_claims_object(self, claims, key): token = jwt.encode(claims, key) assert jwt.get_unverified_claims(token) == claims
Example #25
Source File: test_jwt.py From python-jose with MIT License | 5 votes |
def test_require(self, claims, key, claim, value): options = {"require_" + claim: True, "verify_" + claim: False} token = jwt.encode(claims, key) with pytest.raises(JWTError): jwt.decode(token, key, options=options, audience=str(value)) new_claims = dict(claims) new_claims[claim] = value token = jwt.encode(new_claims, key) jwt.decode(token, key, options=options, audience=str(value))
Example #26
Source File: tokens.py From registry-oauth-server with MIT License | 5 votes |
def encode_token(self): token = jwt.encode(self.claim, self.signing_key, algorithm=self.signing_key_alg, headers=self.header) return token
Example #27
Source File: utils.py From full-stack-fastapi-postgresql with MIT License | 5 votes |
def generate_password_reset_token(email: str) -> str: delta = timedelta(hours=settings.EMAIL_RESET_TOKEN_EXPIRE_HOURS) now = datetime.utcnow() expires = now + delta exp = expires.timestamp() encoded_jwt = jwt.encode( {"exp": exp, "nbf": now, "sub": email}, settings.SECRET_KEY, algorithm="HS256", ) return encoded_jwt
Example #28
Source File: security.py From full-stack-fastapi-postgresql with MIT License | 5 votes |
def create_access_token( subject: Union[str, Any], expires_delta: timedelta = None ) -> str: if expires_delta: expire = datetime.utcnow() + expires_delta else: expire = datetime.utcnow() + timedelta( minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES ) to_encode = {"exp": expire, "sub": str(subject)} encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt
Example #29
Source File: test_jwt.py From python-jose with MIT License | 5 votes |
def test_nbf_datetime(self, key): nbf = datetime.utcnow() - timedelta(seconds=5) claims = { 'nbf': nbf } token = jwt.encode(claims, key) jwt.decode(token, key)
Example #30
Source File: proxy.py From github-pages-basic-auth-proxy with MIT License | 5 votes |
def create_jwt_token(): return jwt.encode({'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=4)}, jwt_secret, algorithm='HS256')