Python jwt.decode() Examples
The following are 30
code examples of jwt.decode().
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: ddb.py From avrae with GNU General Public License v3.0 | 7 votes |
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') )
Example #2
Source File: auth.py From tmessage with GNU General Public License v3.0 | 7 votes |
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"]}')
Example #3
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 #4
Source File: utils.py From django-polaris with Apache License 2.0 | 6 votes |
def generate_interactive_jwt( request: Request, transaction_id: str, account: str ) -> str: """ Generates a 30-second JWT for the client to use in the GET URL for the interactive flow. """ issued_at = time.time() payload = { "iss": request.build_absolute_uri(request.path), "iat": issued_at, "exp": issued_at + 30, "sub": account, "jti": transaction_id, } encoded_jwt = jwt.encode(payload, settings.SERVER_JWT_KEY, algorithm="HS256") return encoded_jwt.decode("ascii")
Example #5
Source File: skill_validation.py From botbuilder-python with MIT License | 6 votes |
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)
Example #6
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 #7
Source File: auth.py From tmessage with GNU General Public License v3.0 | 6 votes |
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"]}')
Example #8
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 #9
Source File: test_decode_tokens.py From flask-jwt-extended with MIT License | 6 votes |
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)
Example #10
Source File: auth.py From selene-backend with GNU Affero General Public License v3.0 | 6 votes |
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
Example #11
Source File: backends.py From aws-workshop with MIT License | 6 votes |
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)
Example #12
Source File: utils.py From full-stack-fastapi-couchbase with MIT License | 6 votes |
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, }, )
Example #13
Source File: policy.py From pyramid_jwt with BSD 2-Clause "Simplified" License | 6 votes |
def create_token(self, principal, expiration=None, audience=None, **claims): payload = self.default_claims.copy() payload.update(claims) payload["sub"] = principal payload["iat"] = iat = datetime.datetime.utcnow() expiration = expiration or self.expiration audience = audience or self.audience if expiration: if not isinstance(expiration, datetime.timedelta): expiration = datetime.timedelta(seconds=expiration) payload["exp"] = iat + expiration if audience: payload["aud"] = audience token = jwt.encode( payload, self.private_key, algorithm=self.algorithm, json_encoder=self.json_encoder, ) if not isinstance(token, str): # Python3 unicode madness token = token.decode("ascii") return token
Example #14
Source File: auth.py From flask-restful-example with MIT License | 6 votes |
def decode_auth_token(cls, token: str): """ 验证token :param token: :return: """ key = current_app.config.get('SECRET_KEY', cls.key) try: # 取消过期时间验证 # payload = jwt.decode(auth_token, config.SECRET_KEY, options={'verify_exp': False}) payload = jwt.decode(token, key=key, ) except (jwt.ExpiredSignatureError, jwt.InvalidTokenError, jwt.InvalidSignatureError): return None else: return payload
Example #15
Source File: token.py From apistar-jwt with MIT License | 6 votes |
def decode(self, token) -> Optional[JWTUser]: try: payload = PyJWT.decode(token, self.secret, algorithms=self.algorithms, **self.options) if payload == {}: return None except PyJWT.MissingRequiredClaimError as exc: log.warning('JWT Missing claim: %s', exc.claim) return None except PyJWT.InvalidTokenError as exc: log.exception('JWT Invalid Token: %s', exc.__class__.__name__) return None except Exception as exc: log.exception('JWT Exception: %s', exc.__class__.__name__) return None _id = payload.get(self.ID) username = payload.get(self.USERNAME) return JWTUser(id=_id, username=username, token=payload)
Example #16
Source File: auth.py From clusterfuzz with Apache License 2.0 | 6 votes |
def _validate_iap_jwt(iap_jwt): """Validate JWT assertion.""" project_id = utils.get_application_id() expected_audience = '/projects/{}/apps/{}'.format( _project_number_from_id(project_id), project_id) try: key_id = jwt.get_unverified_header(iap_jwt).get('kid') if not key_id: raise AuthError('No key ID.') key = _get_iap_key(key_id) decoded_jwt = jwt.decode( iap_jwt, key, algorithms=['ES256'], issuer='https://cloud.google.com/iap', audience=expected_audience) return decoded_jwt['email'] except (jwt.exceptions.InvalidTokenError, requests.exceptions.RequestException) as e: raise AuthError('JWT assertion decode error: ' + str(e))
Example #17
Source File: tutorial004.py From fastapi with MIT License | 6 votes |
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
Example #18
Source File: models.py From AUCR with GNU General Public License v3.0 | 6 votes |
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()
Example #19
Source File: user.py From SempoBlockchain with GNU General Public License v3.0 | 6 votes |
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)
Example #20
Source File: wrappers.py From cloud-inquisitor with Apache License 2.0 | 5 votes |
def __check_auth(self, view): headers = {x[0]: x[1] for x in request.headers} if 'Authorization' in headers: try: token = jwt.decode( headers['Authorization'], get_jwt_key_data() ) if token['auth_system'] != current_app.active_auth_system.name: self.log.error('Token is from another auth_system ({}) than the current one ({})'.format( token['auth_system'], current_app.active_auth_system.name )) return view.make_unauth_response() if has_access(session['user'], self.role): return self.log.error('User {} attempted to access page {} without permissions'.format( session['user'].username, request.path )) return view.make_unauth_response() except (jwt.DecodeError, jwt.ExpiredSignatureError) as ex: session.clear() view.log.info('Failed to decode signature or it had expired: {0}'.format(ex)) return view.make_unauth_response() session.clear() view.log.info('Failed to detect Authorization header') return view.make_unauth_response()
Example #21
Source File: token_manager.py From Paradrop with Apache License 2.0 | 5 votes |
def decode(self, token): """ Decode a JWT that was issued by us. Throws an InvalidTokenError on decoding failure or token expiration. """ return jwt.decode(token, self.secret, algorithms=['HS256'])
Example #22
Source File: tutorial005.py From fastapi with MIT License | 5 votes |
def get_current_user( security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme) ): if security_scopes.scopes: authenticate_value = f'Bearer scope="{security_scopes.scope_str}"' else: authenticate_value = f"Bearer" credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": authenticate_value}, ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) username: str = payload.get("sub") if username is None: raise credentials_exception token_scopes = payload.get("scopes", []) token_data = TokenData(scopes=token_scopes, username=username) except (PyJWTError, ValidationError): raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: raise credentials_exception for scope in security_scopes.scopes: if scope not in token_data.scopes: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Not enough permissions", headers={"WWW-Authenticate": authenticate_value}, ) return user
Example #23
Source File: jwt_token_extractor.py From botbuilder-python with MIT License | 5 votes |
def _has_allowed_issuer(self, jwt_token: str) -> bool: decoded = jwt.decode(jwt_token, verify=False) issuer = decoded.get("iss", None) if issuer in self.validation_parameters.issuer: return True return issuer == self.validation_parameters.issuer
Example #24
Source File: models.py From AUCR with GNU General Public License v3.0 | 5 votes |
def get_token(self, expires_in=360000): """Generate and return a token for user auth.""" now = udatetime.utcnow().replace(tzinfo=None) if self.token and self.token_expiration > now - timedelta(seconds=60): return self.token self.token = base64.b64encode(os.urandom(64)).decode('utf-8') self.token_expiration = now + timedelta(seconds=expires_in) db.session.add(self) return self.token
Example #25
Source File: models.py From AUCR with GNU General Public License v3.0 | 5 votes |
def verify_reset_password_token(token): """Check reset password token and return outcome.""" try: user_id = jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=['HS256'])['reset_password'] except AttributeError: return return User.query.get(user_id)
Example #26
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 #27
Source File: emulator_validation.py From botbuilder-python with MIT License | 5 votes |
def is_token_from_emulator(auth_header: str) -> bool: """ Determines if a given Auth header is from the Bot Framework Emulator :param auth_header: Bearer Token, in the 'Bearer [Long String]' Format. :type auth_header: str :return: True, if the token was issued by the Emulator. Otherwise, false. """ from .jwt_token_validation import ( # pylint: disable=import-outside-toplevel 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) if not token: return False # Is there an Issuer? issuer = token["iss"] if not issuer: # No Issuer, means it's not from the Emulator. return False # Is the token issues by a source we consider to be the emulator? issuer_list = ( EmulatorValidation.TO_BOT_FROM_EMULATOR_TOKEN_VALIDATION_PARAMETERS.issuer ) if issuer_list and not issuer in issuer_list: # Not a Valid Issuer. This is NOT a Bot Framework Emulator Token. return False # The Token is from the Bot Framework Emulator. Success! return True
Example #28
Source File: user.py From SempoBlockchain with GNU General Public License v3.0 | 5 votes |
def encode_single_use_JWS(self, token_type): s = TimedJSONWebSignatureSerializer(current_app.config['SECRET_KEY'], expires_in=current_app.config['TOKEN_EXPIRATION']) return s.dumps({'id': self.id, 'type': token_type}).decode("utf-8")
Example #29
Source File: jwt_token_extractor.py From botbuilder-python with MIT License | 5 votes |
def _validate_token( self, jwt_token: str, channel_id: str, required_endorsements: List[str] = None ) -> ClaimsIdentity: required_endorsements = required_endorsements or [] headers = jwt.get_unverified_header(jwt_token) # Update the signing tokens from the last refresh key_id = headers.get("kid", None) metadata = await self.open_id_metadata.get(key_id) if key_id and metadata.endorsements: # Verify that channelId is included in endorsements if not EndorsementsValidator.validate(channel_id, metadata.endorsements): raise Exception("Could not validate endorsement key") # Verify that additional endorsements are satisfied. # If no additional endorsements are expected, the requirement is satisfied as well for endorsement in required_endorsements: if not EndorsementsValidator.validate( endorsement, metadata.endorsements ): raise Exception("Could not validate endorsement key") if headers.get("alg", None) not in self.validation_parameters.algorithms: raise Exception("Token signing algorithm not in allowed list") options = { "verify_aud": False, "verify_exp": not self.validation_parameters.ignore_expiration, } decoded_payload = jwt.decode( jwt_token, metadata.public_key, leeway=self.validation_parameters.clock_tolerance, options=options, ) claims = ClaimsIdentity(decoded_payload, True) return claims
Example #30
Source File: auth.py From selene-backend with GNU Affero General Public License v3.0 | 5 votes |
def generate(self, account_id): """ Generates a JWT token """ self.account_id = account_id payload = dict( iat=datetime.utcnow(), exp=time() + self.duration, sub=account_id ) token = jwt.encode(payload, self.secret, algorithm='HS256') # convert the token from byte-array to string so that # it can be included in a JSON response object self.jwt = token.decode()