本文整理汇总了Python中jwt.decode方法的典型用法代码示例。如果您正苦于以下问题:Python jwt.decode方法的具体用法?Python jwt.decode怎么用?Python jwt.decode使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类jwt
的用法示例。
在下文中一共展示了jwt.decode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: is_skill_token
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import decode [as 别名]
def is_skill_token(auth_header: str) -> bool:
"""
Determines if a given Auth header is from from a skill to bot or bot to skill request.
:param auth_header: Bearer Token, in the "Bearer [Long String]" Format.
:return bool:
"""
from .jwt_token_validation import JwtTokenValidation
if not JwtTokenValidation.is_valid_token_format(auth_header):
return False
bearer_token = auth_header.split(" ")[1]
# Parse the Big Long String into an actual token.
token = jwt.decode(bearer_token, verify=False)
return SkillValidation.is_skill_claim(token)
示例2: encode_jwt
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import decode [as 别名]
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")
示例3: decode_jwt
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import decode [as 别名]
def decode_jwt(jwt_value):
"""
:type jwt_value: str
"""
try:
headers_enc, payload_enc, verify_signature = jwt_value.split(".")
except ValueError:
raise jwt.InvalidTokenError()
payload_enc += '=' * (-len(payload_enc) % 4) # add padding
payload = json.loads(base64.b64decode(payload_enc).decode("utf-8"))
algorithms = getattr(settings, 'JWT_JWS_ALGORITHMS', ['HS256', 'RS256'])
public_key_name = 'JWT_PUBLIC_KEY_{}'.format(payload['iss'].upper())
public_key = getattr(settings, public_key_name, None)
if not public_key:
raise ImproperlyConfigured('Missing setting {}'.format(
public_key_name))
decoded = jwt.decode(jwt_value, public_key, algorithms=algorithms)
return decoded
示例4: _jwt_for_user
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import decode [as 别名]
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
示例5: _parse_jwt
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import decode [as 别名]
def _parse_jwt(token: str):
"""
Parses a JWT from the Auth Service into a DDB User.
:param str token: The JWT returned by the Auth Service.
:return: The DDB user represented by the JWT.
:rtype: BeyondUser
"""
payload = jwt.decode(token, WATERDEEP_SECRET, algorithms=['HS256'],
issuer=ISSUER, audience=[AUDIENCE, ISSUER], verify=True)
return BeyondUser(
token,
payload['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier'],
payload['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name'],
payload.get('http://schemas.microsoft.com/ws/2008/06/identity/claims/role', []),
payload.get('http://schemas.dndbeyond.com/ws/2019/08/identity/claims/subscriber'),
payload.get('http://schemas.dndbeyond.com/ws/2019/08/identity/claims/subscriptiontier')
)
示例6: authenticate
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import decode [as 别名]
def authenticate(user_name, password):
""" Authenticate already registered User """
endpoint_url = f'{API_USER_URL}/login'
headers = {
"Content-Type": "application/json"
}
credential = {
"user_name": user_name,
"password": password
}
response = r.post(endpoint_url, json=credential, headers=headers)
if response.status_code == 200:
data = response.json()
return jwt.decode(data['token'], verify=False)
error = response.json()
raise Exception(f'Error Authenticating User: {error["message"]}')
示例7: register
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import decode [as 别名]
def register(user_name, displayed_name, password, password_confirm):
""" Register a new User """
endpoint_url = f'{API_USER_URL}/register'
headers = {
"Content-Type": "application/json"
}
new_user = {
"user_name": user_name,
"displayed_name": displayed_name,
"password": password,
"password_confirm": password_confirm
}
response = r.post(endpoint_url, json=new_user, headers=headers)
if response.status_code == 200:
data = response.json()
return jwt.decode(data['token'], verify=False)
error = response.json()
raise Exception(f'Error Registering User: {error["message"]}')
示例8: send_reset_password_email
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import decode [as 别名]
def send_reset_password_email(email_to: str, username: str, token: str):
project_name = config.PROJECT_NAME
subject = f"{project_name} - Password recovery for user {username}"
with open(Path(config.EMAIL_TEMPLATES_DIR) / "reset_password.html") as f:
template_str = f.read()
if hasattr(token, "decode"):
use_token = token.decode()
else:
use_token = token
server_host = config.SERVER_HOST
link = f"{server_host}/reset-password?token={use_token}"
send_email(
email_to=email_to,
subject_template=subject,
html_template=template_str,
environment={
"project_name": config.PROJECT_NAME,
"username": username,
"email": email_to,
"valid_hours": config.EMAIL_RESET_TOKEN_EXPIRE_HOURS,
"link": link,
},
)
示例9: _encode_jwt
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import decode [as 别名]
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
示例10: test_legacy_decode_key_callback
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import decode [as 别名]
def test_legacy_decode_key_callback(app, default_access_token):
jwtM = get_jwt_manager(app)
app.config['JWT_SECRET_KEY'] = 'foobarbaz'
# test decode key callback with one argument (backwards compatibility)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
@jwtM.decode_key_loader
def get_decode_key_legacy(claims):
return 'foobarbaz'
with app.test_request_context():
token = encode_token(app, default_access_token)
decode_token(token)
assert len(w) == 1
assert issubclass(w[-1].category, DeprecationWarning)
示例11: validate
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import decode [as 别名]
def validate(self):
"""Decodes the auth token and performs some preliminary validation."""
self.is_expired = False
self.is_valid = True
self.account_id = None
if self.jwt is None:
self.is_expired = True
else:
try:
payload = jwt.decode(self.jwt, self.secret)
self.account_id = payload['sub']
except jwt.ExpiredSignatureError:
self.is_expired = True
except jwt.InvalidTokenError:
self.is_valid = False
示例12: decode_auth_token
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import decode [as 别名]
def decode_auth_token(auth_token, token_type='Auth'):
"""
Validates the auth token
:param auth_token:
:return: integer|string
"""
try:
payload = jwt.decode(auth_token, current_app.config.get(
'SECRET_KEY'), algorithms='HS256')
is_blacklisted_token = BlacklistToken.check_blacklist(auth_token)
if is_blacklisted_token:
return 'Token blacklisted. Please log in again.'
else:
return payload
except jwt.ExpiredSignatureError:
return '{} Token Signature expired.'.format(token_type)
except jwt.InvalidTokenError:
return 'Invalid {} Token.'.format(token_type)
示例13: _authenticate_credentials
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import decode [as 别名]
def _authenticate_credentials(self, request, token):
"""
Try to authenticate the given credentials. If authentication is
successful, return the user and token. If not, throw an error.
"""
try:
payload = jwt.decode(token, settings.SECRET_KEY)
except:
msg = 'Invalid authentication. Could not decode token.'
raise exceptions.AuthenticationFailed(msg)
try:
user = User.objects.get(pk=payload['id'])
except User.DoesNotExist:
msg = 'No user matching this token was found.'
raise exceptions.AuthenticationFailed(msg)
if not user.is_active:
msg = 'This user has been deactivated.'
raise exceptions.AuthenticationFailed(msg)
return (user, token)
示例14: insert_initial_user_values
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import decode [as 别名]
def insert_initial_user_values(*args, **kwargs):
"""Create default database values from auth yaml template file."""
run = YamlInfo("aucr_app/plugins/auth/auth.yml", "none", "none")
admin_data = run.get()
for items in admin_data:
hashed_password = generate_password_hash(admin_data[items]["password"]).decode('utf-8')
default_groups = Groups.__call__(name="admin")
default_user_groups = Groups.__call__(name="user")
default_system_groups = Groups.__call__(name="system")
db.session.add(default_groups)
db.session.add(default_user_groups)
db.session.add(default_system_groups)
db.session.commit()
default_admin = User.__call__(username=items, password_hash=hashed_password, email=admin_data[items]["email"])
admin_group = Group.__call__(groups_id=1, username_id=1)
user_group = Group.__call__(groups_id=2, username_id=1)
db.session.add(admin_group)
db.session.add(user_group)
db.session.add(default_admin)
db.session.commit()
示例15: get_current_user
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import decode [as 别名]
def get_current_user(token: str = Depends(oauth2_scheme)):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise credentials_exception
token_data = TokenData(username=username)
except PyJWTError:
raise credentials_exception
user = get_user(fake_users_db, username=token_data.username)
if user is None:
raise credentials_exception
return user