本文整理匯總了Python中jose.jwt.encode方法的典型用法代碼示例。如果您正苦於以下問題:Python jwt.encode方法的具體用法?Python jwt.encode怎麽用?Python jwt.encode使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類jose.jwt
的用法示例。
在下文中一共展示了jwt.encode方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: validate
# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import encode [as 別名]
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.")
示例2: test_init_bad_sig_token_given_no_verify
# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import encode [as 別名]
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,
)
示例3: test_str
# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import encode [as 別名]
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',
),
)
示例4: test_no_alg
# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import encode [as 別名]
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=[])
示例5: test_encode
# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import encode [as 別名]
def test_encode(self, claims, key):
expected = (
(
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9'
'.eyJhIjoiYiJ9'
'.xNtk2S0CNbCBZX_f67pFgGRugaP1xi2ICfet3nwOSxw'
),
(
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9'
'.eyJhIjoiYiJ9'
'.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8'
)
)
encoded = jwt.encode(claims, key)
assert encoded in expected
示例6: test_nbf_skip
# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import encode [as 別名]
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)
示例7: test_exp_skip
# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import encode [as 別名]
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)
示例8: create_jwt
# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import encode [as 別名]
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
示例9: generate
# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import encode [as 別名]
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])
示例10: login
# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import encode [as 別名]
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})
示例11: create_jwt_token
# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import encode [as 別名]
def create_jwt_token():
return jwt.encode({'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=4)}, jwt_secret, algorithm='HS256')
示例12: test_init_bad_sig_token_given
# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import encode [as 別名]
def test_init_bad_sig_token_given(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
with self.assertRaises(TokenError):
MyToken(invalid_token)
示例13: test_non_default_alg
# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import encode [as 別名]
def test_non_default_alg(self, claims, key):
encoded = jwt.encode(claims, key, algorithm='HS384')
decoded = jwt.decode(encoded, key, algorithms='HS384')
assert claims == decoded
示例14: test_non_default_alg_positional_bwcompat
# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import encode [as 別名]
def test_non_default_alg_positional_bwcompat(self, claims, key):
encoded = jwt.encode(claims, key, 'HS384')
decoded = jwt.decode(encoded, key, 'HS384')
assert claims == decoded
示例15: test_no_alg_default_headers
# 需要導入模塊: from jose import jwt [as 別名]
# 或者: from jose.jwt import encode [as 別名]
def test_no_alg_default_headers(self, claims, key, headers):
token = jwt.encode(claims, key, algorithm='HS384')
b64header, b64payload, b64signature = token.split('.')
bad_token = b64header + '.' + b64payload
with pytest.raises(JWTError):
jwt.get_unverified_headers(bad_token)