def test_decode(self): # check that we can't decode with the wrong secret payload = {'foo': 'bar'} encoded = jwt_encode(payload, "QWERTYUIO") self.assertRaises(DecodeError, decode, encoded) # we can decode this, but we're missing the mandatory fields encoded = jwt_encode(payload, settings.SECRET_KEY) self.assertRaises(MissingRequiredClaimError, decode, encoded) # force all mandatory claims into the payload payload = {k: 'foo' for k in MANDATORY_CLAIMS} encoded = jwt_encode(payload, settings.SECRET_KEY) self.assertEqual(decode(encoded), payload) self.assertEqual(decode(encoded), jwt_decode(encoded, settings.SECRET_KEY))
async def return_user_and_token(request: Request, user): jwt_token = jwt_encode( { 'uid': ItHashids.encode(user.id), 'name': user.name, 'dep': user.department, 'rol': user.role, 'pho': user.phone, 'email': user.email, 'iat': round(datetime.now().timestamp()), 'exp': round((datetime.now() + timedelta(hours=24)).timestamp()) }, request.app['config']['jwt-secret'], algorithm='HS256').decode('utf-8') await request.app['redis'].set('{}:{}:jwt'.format(user.name, user.department), jwt_token, expire=60 * 60 * 24) # 这是为了禁止重复登录 return code_response( ResponseOk, { 'token': jwt_token, 'user': { 'name': user.name, 'department': user.department, 'role': user.role, 'phone': user.phone, 'email': user.email, } })
def setUp(self): self.user = User.objects.create_user(username='******', email='*****@*****.**', password='******') self.jwt_token = jwt_encode({'user_id': str(self.user.id)}, settings.SECRET_KEY, algorithm='HS256')
def create(self, issued_at: Optional[datetime] = None) -> str: """ Create the actual token from the :class:`EasyJWT` object. Empty optional claims will not be included in the token. Empty non-optional claims will cause a :class:`MissingRequiredClaimsError`. :param issued_at: The date and time at which this token was issued. If not given, the current date and time will be used. Must be given in UTC. Defaults to `None`. :return: The token represented by the current state of the object. :raise IncompatibleKeyError: If the given key is incompatible with the algorithm used for encoding the token. :raise MissingRequiredClaimsError: If instance variables that map to non-optional claims in the claim set are empty. """ # Set the issued-at date. self.issued_at_date = issued_at if self.issued_at_date is None: self.issued_at_date = datetime.utcnow().replace(microsecond=0) # Fail if there are empty required claims. missing_claims = self._get_required_empty_claims() if len(missing_claims) > 0: raise MissingRequiredClaimsError(missing_claims) # Encode the object. claim_set = self._get_claim_set() try: token = jwt_encode(claim_set, self._key, algorithm=self.algorithm.value) except JWT_InvalidKeyError as error: raise IncompatibleKeyError(str(error)) return token
def _create_token(expired=True, session_id=randint(1, 6), expired_time=None): expires = expired_time or datetime.now() + timedelta(seconds=6) encode_tk = jwt_encode({ "session_id": session_id, "expires": expires.strftime("%a, %d %b %Y %H:%M:%S GMT") if expired else None, }, key=jwe_settings.get("key")) return encode_tk
async def create_internal_auth_token( internal_user: InternalUser) -> InternalAuthToken: """ Creates a one time JWT authentication token to return to the user. The token is used as a key to cache the user's internal id until he requests for an access token when it is removed from the cache. Args: internal_user: A user object that has meaning in this application Returns: encoded_jwt: The encoded JWT authentication token """ expires_delta = datetime.timedelta( minutes=int(config.AUTH_TOKEN_EXPIRE_MINUTES)) expire = datetime.datetime.utcnow() + expires_delta to_encode = dict(exp=expire) encoded_jwt = jwt_encode(to_encode, config.JWT_SECRET_KEY, algorithm=config.ALGORITHM).decode('utf-8') # Add token/user pair in the cache await cache.set(encoded_jwt, internal_user.internal_sub_id) return encoded_jwt
def test_encode(self): payload = {'foo': 'bar'} self.assertRaises(MissingRequiredClaimError, encode, payload) # force all mandatory claims into the payload payload = {k: 'foo' for k in MANDATORY_CLAIMS} self.assertEqual(encode(payload), jwt_encode(payload, settings.SECRET_KEY))
async def return_user_and_token_unregister(request: Request, user, resp): jwt_token = jwt_encode( { 'wxId': user['wx_id'], 'name': user['name'], 'number': user['number'], 'dep': '', 'rol': 0, 'pho': user['mobile'], 'email': '', 'iat': round(datetime.now().timestamp()), 'exp': round((datetime.now() + timedelta(hours=24)).timestamp()) }, request.app['config']['jwt-secret'], algorithm='HS256').decode('utf-8') await request.app['redis'].set('{}:unregister:jwt'.format(user['name']), jwt_token, expire=60 * 5) # 这是为了禁止重复登录 return code_response( resp, { 'token': jwt_token, 'user': { 'wxId': user['wx_id'], 'name': user['name'], 'number': user['number'], 'phone': user['mobile'], } })
def remember_me_token(self, secret, timedelta, issuer, algorithm='HS256'): payload = { 'exp': datetime.datetime.utcnow() + timedelta, 'iat': datetime.datetime.utcnow(), 'iss': issuer, 'sub': self.id } return jwt_encode(payload, secret, algorithm=algorithm)
def test_decode__invalid_algo(self): # check that we can't decode with the wrong algorithms payload = {"foo": "bar"} encoded = jwt_encode(payload, settings.SECRET_KEY) self.assertRaises(InvalidAlgorithmError, decode, encoded, algorithms=["HS384"])
def create_id_token(private_key: str, user: dict) -> str: user_data = { "iss": "http://arch.homework", "exp": datetime.utcnow() + timedelta(minutes=15), "sub": user["id"], "name": user["name"] } result = jwt_encode(user_data, private_key, algorithm='RS256', headers={'kid': '1'}) return result
def encode(payload, secret='zn1xct1RFpGvuyXC3E9BreRjVl9x1GxQ', algorithm="HS512"): payload = JWT.add_jwt_signatures(payload) encoded = jwt_encode(payload, secret, algorithm=algorithm).decode('utf-8') return encoded
def test_access_info_blocks_access_due_to_server_error(self): claims = { "iss": f'http://{self.server_thread.address[0]}:12345/' # This issuer is inaccessible. } problematic_jwt = jwt_encode(claims, None, None).decode() with AuthResponseHelper(self.base_url): response = requests.get(f'{self.base_url}/me', headers=dict(Authorization=f'Bearer {problematic_jwt}')) self.assertEqual(403, response.status_code)
def get_jwt(self, text_): payload = { 'id': text_['memberId'], 'exp': datetime.utcnow() # 必须要用utc } token = jwt_encode(payload, self.application.settings['secret_key'], algorithm='HS256') return token.decode('utf8')
def generate_token(u_id): secret = get_secret() token_bytes = jwt_encode( { 'u_id': u_id, 'timestamp': time() }, secret, algorithm='HS256' ) token = token_bytes.decode('utf-8') return token
def create_jwt(self): payload = { # Issued at time 'iat': int(datetime.now().timestamp()), # JWT expiration time (10 minute maximum) 'exp': int((datetime.now() + timedelta(minutes=9)).timestamp()), # GitHub App's identifier 'iss': self.app_id } return jwt_encode(payload, self.pk, algorithm='RS256')
def password_reset_token(self, expires_in=600): """Returns a signed password reset token that expires in 'expires_in' seconds (defaults to 600).""" return jwt_encode( { 'password_reset_for_email': str(self.email), 'exp': time() + expires_in }, current_app.config['SECRET_KEY'], algorithm='HS256').decode('utf-8')
def encode_payload( self, _payload: Optional[TPayload] = None, **claims ) -> EncodedToken[TPayload]: payload = _payload or self.create_payload(**claims) token = jwt_encode( payload.dict(exclude_unset=True), key=self.encode_key, algorithm=self.encode_algorithm, json_encoder=make_json_encoder(self.payload_type), ).decode() return self.encoded_token_type(token=token, payload=payload)
def verification_token(self, expires_in=1209600): """Returns a signed email verification token that expires in 'expires_in' seconds (defaults to 1209600 or 14 days).""" return jwt_encode( { 'email': self.email, 'user_id': self.user_id, 'exp': time() + expires_in }, current_app.config['SECRET_KEY'], algorithm='HS256').decode('utf-8')
def json_and_response_code(request): if "clientToken" not in request.json or request.json["clientToken"] is None: return NULL_CLIENT_TOKEN.dual if "accessToken" not in request.json or request.json["accessToken"] is None: return NULL_ACCESS_TOKEN.dual access_token = AccessToken.from_token(request.json["accessToken"]) try: if access_token is None or access_token.client_token.uuid != UUID( request.json["clientToken"]): return INVALID_TOKEN.dual except ValueError: return INVALID_UUID.dual if "selectedProfile" in request.json: try: _selected_uuid = UUID(request.json["selectedProfile"]["id"]) except ValueError: return INVALID_UUID.dual new_profile = Profile.get( lambda x: x.uuid == _selected_uuid and x.name == request.json[ "selectedProfile"][ "name"] and x.account == access_token.client_token.account) if new_profile is None: return PROFILE_NOT_FOUND.dual else: new_profile = access_token.profile new_access_token = AccessToken( client_token=access_token.client_token, profile=new_profile, ) access_token.delete() response_data = { "accessToken": jwt_encode(new_access_token.format(), key="").decode(), "clientToken": request.json["clientToken"], } if new_access_token.profile: response_data["selectedProfile"] = { "id": new_access_token.profile.uuid.hex, "name": new_access_token.profile.name } if "requestUser" in request.json and request.json["requestUser"]: response_data["user"] = { "id": new_access_token.client_token.account.uuid.hex, "username": new_access_token.client_token.account.username } return jsonify(response_data), 200
def _generate_jwt_token(self): """ Generates a JSON Web Token that stores this user's ID and has an expiry date set to 60 days into the future. """ dt = datetime.now() + timedelta(days=60) token = jwt_encode(dict(id=self.pk, exp=int(dt.strftime('%s'))), settings.SECRET_KEY, algorithm='HS256') return token.decode('utf-8')
def sendReply(self, reply: Dict[str, Any]) -> None: self.set_header("Content-type", "application/jwt") jwt_reply = dict(reply) jwt_reply.update({ 'iat': datetime.utcnow(), 'nbf': datetime.utcnow() - self.NBF_LEEWAY, 'exp': datetime.utcnow() + self.VALID_FOR, 'jti': self.jti }) self.write( jwt_encode(jwt_reply, algorithm='HS256', key=self.settings['api_key'])) self.finish()
async def update_token(content: dict, old_token: str, app): """ 设置新的颁发时间和过期时间 """ content['iat'] = round(datetime.now().timestamp()), content['exp'] = round((datetime.now() + timedelta(hours=24)).timestamp()) new_token = jwt_encode(content, app['config']['jwt-secret'], algorithm='HS256').decode('utf-8') await app['black_bf'].insert(old_token) # 更新token时预留的缓冲时间 await app['redis'].set( key='it:tmp-list:{}'.format(old_token), value=new_token, expire=30, ) return new_token
def encode(self, private_key: RSAPrivateKey) -> bytes: private_bytes = private_key.private_bytes( encoding=Encoding.PEM, format=PrivateFormat.TraditionalOpenSSL, encryption_algorithm=NoEncryption()) public_key = private_key.public_key() numbers = public_key.public_numbers() n = numbers.n.to_bytes(int(public_key.key_size / 8), 'big').lstrip(b'\x00') kid = sha1(n).hexdigest() payload = self.payload() return jwt_encode(payload, private_bytes, algorithm='RS256', headers={'kid': kid})
async def create_internal_access_token( access_token_data: InternalAccessTokenData) -> str: """ Creates a JWT access token to return to the user. Args: access_token_data: The data to be included in the JWT access token Returns: encoded_jwt: The encoded JWT access token """ expires_delta = datetime.timedelta( minutes=int(config.ACCESS_TOKEN_EXPIRE_MINUTES)) to_encode = access_token_data.dict() expire = datetime.datetime.utcnow() + expires_delta to_encode.update(dict(exp=expire)) encoded_jwt = jwt_encode(to_encode, config.JWT_SECRET_KEY, algorithm=config.ALGORITHM) return encoded_jwt.decode('utf-8')
def generate_jwt(kid, privkey, client_id, alg="RS256"): aud = f"{get_base_url()}/oxauth/restv1/token" now = datetime.utcnow() expire = timedelta(days=2) + now headers = { "typ": "JWT", "alg": alg, "kid": kid, } payload = { # This is my client ID "iss": client_id, # This is also my client ID "sub": client_id, # This is the time which this JWT will be expired. You can get epoch time from an epoch time from https://www.epochconverter.com "exp": expire, # This is the time which this jwt is created. Again use an approximate value. This can be any value in history "iat": now, # This has to be unique in every JWT you send out in a request. You can't repeat this value. "jti": str(uuid.uuid4()), "aud": aud, } return jwt_encode(payload, privkey, algorithm=alg, headers=headers)
def encode(payload, check_claims=MANDATORY_CLAIMS): """Encode JSON payload (using SECRET_KEY).""" check_mandatory_claims(payload, claims=check_claims) return jwt_encode(payload, settings.SECRET_KEY)
def test_decode__wrong_secret(self): # check that we can't decode with the wrong secret payload = {k: "foo" for k in MANDATORY_CLAIMS} encoded = jwt_encode(payload, "QWERTYUIO") self.assertRaises(DecodeError, decode, encoded)
def encode(identity): return jwt_encode({'identity': identity}, config.app['at_string'], algorithm='HS256')
def test_decode__missing_claims(self): # we can decode this, but we're missing the mandatory fields payload = {"foo": "bar"} encoded = jwt_encode(payload, settings.SECRET_KEY) self.assertRaises(MissingRequiredClaimError, decode, encoded)