def gen_user_token(user): claims = { 'user_name': user.login, 'authorities': user.authorities, 'scope': ['openid'], 'client_id': 'web_app' } try: access_token = python_jwt.generate_jwt( claims, priv_key=jwk.JWK.from_pem(g.config.private_key), algorithm='RS256', lifetime=datetime.timedelta(seconds=300), # 5 min jti_size=16) except: return None try: jwt_decoded = python_jwt.verify_jwt(access_token, pub_key=jwk.JWK.from_pem( g.config.public_key), allowed_algs=['RS256'], checks_optional=True, ignore_not_implemented=True) except: return None try: refresh_token = python_jwt.generate_jwt( claims, priv_key=jwk.JWK.from_pem(g.config.private_key), algorithm='RS256', lifetime=datetime.timedelta(seconds=604800), # 7 days jti_size=16) except: return None result = { 'access_token': access_token, 'refresh_token': refresh_token, 'token_type': 'bearer', 'scope': 'web-app', 'iat': jwt_decoded[1].get('iat'), 'exp': jwt_decoded[1].get('exp'), 'expires_in': jwt_decoded[1].get('exp') - jwt_decoded[1].get('iat') - 1, 'jti': jwt_decoded[1].get('jti') } return result
async def test_login_refreshes_with_refresh_token(test_client, user1, monkeypatch, mocker): # This test is giving me a headache. It's kind of a convenience feature...and it # works. I just can't get a test to work correctly. payload = {"iss": f"{os.getenv('HOST')}/0", "sub": user1.email} portal = await ensure_portal_app() new_id_token = jwt.generate_jwt(payload, portal.get_key(), "ES256", datetime.timedelta(minutes=5)) async def fake_refresh(*_args): return new_id_token mocker.patch( "app.portal.routes.auth.auth_client.verify", side_effect=[ # AuthenticationFailure("expired"), { "headers": { "alg": "ES256", "typ": "JWT" }, "claims": { "iss": os.getenv("HOST"), "sub": user1.email, }, }, ], ) monkeypatch.setattr("app.portal.security.pac.AuthClient.refresh", fake_refresh) id_token = jwt.generate_jwt(payload, portal.get_key(), "ES256", datetime.timedelta(seconds=0)) refresh_token = await token.generate_refresh_token(user1.email, portal) response = test_client.get( "/login", cookies={ # "id_token": "", "refresh_token": refresh_token, }, ) assert response.ok assert "Dashboard" in response.text assert "Your Apps" in response.text # With the 307 redirect, there will be a new get request from the final request that # should have the cookie set from the refresh in the login view. print(response.request._cookies["id_token"]) assert response.request._cookies.get("id_token").value == new_id_token
def f(_): """ Generate token """ passwd = '1234' print(passwd) password = '******' print(password) result = eval(alg) output = os.system(result['1']) key = RSA.generate(512, os.urandom) print(key.exportKey('OpenSSH')) exec("setname('%s')" % alg) privk = priv_keys[alg].get('default', priv_key) jwt.generate_jwt(payload, privk, alg, timedelta(seconds=5))
def register(): data = request.json user = data['username'] passw = data['password'] #print("recibi:") print("usuario:" + user) print("password:"******"\n\n") #pass2 = data['pass2'] #p = users.has_key(param) cnx = None try: cnx = pymysql.connect(**mysql_config) cursor = cnx.cursor() query = "SELECT `usuario` FROM `usuarios` WHERE `usuario`= %s" cursor.execute(query, user) resp = cursor.fetchone() #print(resp) # print("result:") # print(resp) if (not resp): #si no existe podemos registrarlo print("El usuario no existe") #insertamos en la base de datos insert = "INSERT INTO usuarios (usuario, password) VALUES (%s, %s)" usuario = (user, passw) cursor.execute(insert, usuario) cnx.commit() cursor.close() payload = { 'username': user, 'role': 'admin' } token = jwt.generate_jwt(payload, private_key, 'RS256', datetime.timedelta(minutes=5)) ret = { "status": "OK", "msg": "usuario creado correctamente", "token": token } return ret else: print("usuario existe en la base de datos") #cnx.commit() cursor.close() ret = {"status": "FAIL", "msg": "usuario ya existe."} #cnx.commit() cursor.close() except pymysql.Error as err: print "Failed to insert data: {}".format(err) ret = {"status": "FAIL", "msg": err} finally: if cnx: cnx.close() return ret
def GetToken(self, username, password): try: db = NWD_DB() sub = db.authenticate_user(username, password)[0] if sub != '': key = jwk.JWK.generate(kty='RSA', size=2048) userinfo = db.get_user_info(sub) payload = { 'fname': userinfo['fname'], 'lname': userinfo['lname'], 'phone': userinfo['phone'], 'email': userinfo['email'], 'datejoined': userinfo['datejoined'], 'sub': userinfo['user_id'], } token = jwt.generate_jwt(payload, key, 'PS256', datetime.timedelta(days=1)) header, claims = jwt.verify_jwt(token, key, ['PS256']) for k in payload: assert claims[k] == payload[k] return token else: return '' except: return ''
def generate_token(payload): private_key_file = os.path.join(os.path.dirname(__file__), 'keypair.priv') with open(private_key_file, 'r') as fd: private_key = RSA.importKey(fd.read()) token = jwt.generate_jwt(payload, private_key, 'RS256', datetime.timedelta(minutes=5)) return token
def _generate(): uid = str(uuid.uuid4()) payload = { "iss": f"{config.ISSUER}/{fake_refresh_client_app.app_id}", "sub": fake_email, "uid": uid, } refresh_token = jwt.generate_jwt( payload, fake_refresh_client_app.get_refresh_key(), "ES256", datetime.timedelta( hours=fake_refresh_client_app.refresh_token_expire_hours), ) mocker.patch("mongox.Model.delete") expires = datetime.datetime.now() + datetime.timedelta(hours=24) _saved = RefreshToken( app_id=fake_refresh_client_app.app_id, email=fake_email, hash=pwd_context.hash(refresh_token), expires=expires, uid=uid, ) return _saved
def encode_jwt(payload: dict, token_type: TokenType) -> str: exp = (settings.JWT_EXPIRATION_DELTA if token_type is TokenType.ACCESS else settings.JWT_REFRESH_EXPIRATION_DELTA) jti_size = (settings.JWT_JTI_SIZE if settings.JWT_BLACKLIST_ENABLED and token_type.value in settings.JWT_BLACKLIST_TOKEN_CHECKS else 0) payload["type"] = token_type.value token = generate_jwt( payload, _secret_key, algorithm=settings.JWT_ALGORITHM, lifetime=exp, jti_size=jti_size, ) if settings.JWT_ENCRYPT: token = JWE( plaintext=token.encode("utf-8"), protected={ "alg": settings.JWE_ALGORITHM, "enc": settings.JWE_ENCRYPTION, "typ": "JWE", }, ) token.add_recipient(_encryption_key) token = token.serialize() return token
def post(self, request, *args, **kwargs): service_account_email = "*****@*****.**" private_key = RSA.importKey( "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDrURIqajzmeCta\nF81Sbw3h897nQs+n5bu1E6FALCR0JZd6EEDHBOyJt0T4fLFR948cfsOUOeDTCzL3\nbpcg2i0qegFkJjaFG8798Ao/AaphAw4D6GH1ZS+5vxGvisvRmc4xHkIQeZek75Y4\nThFlPOGL9Qqq2mUiQ+7BNv35R5FAGPC3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usZPQKBgCFv\nXcPCbzHFJT42bWI0QMeBtZb0GQdr0ubCJyC2BpumMe12SkGf3Lvb/v0ri36Bq98X\n8BpDXTGHdcSa/wDdcWsUJXiWKRjDD+dj8+nNJwJ9DHuronjxdkCT56n2BaKfrA7x\nolmGDeweQNmeabVTBhx4qBeyI1jF0N5tu9rIlUkTAoGAH0R5YyQtYRnKZGhLm4C7\np1CNSZVmQcIvSjO64cCugwBFkoFb9ghY4252tMBYSXEAJ51GEynhRRYEVqEBC8up\n7FS5mGklBbORYkwZg+puRddYKZ+9EeR9STBoaZnRoM2/8dbv48oOPTqgRYZvRBWA\nFCKVGdkDCNmKoOzEobCUsNI=\n-----END PRIVATE KEY-----\n" ) try: payload = { "iss": service_account_email, "sub": service_account_email, "aud": "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit", "uid": request.data.get('uid') } exp = datetime.timedelta(minutes=60) return HttpResponse( json.dumps({ 'status': 'success', 'key': jwt.generate_jwt(payload, private_key, "RS256", exp) })) except Exception as e: return HttpResponse(json.dumps({'status': 'error + ' + str(e)})) return None
async def generate_refresh_token(email: str, client_app: ClientApp) -> str: if not client_app.get_refresh_key( ) or not client_app.refresh_token_expire_hours: raise TokenCreationError("Refresh is not enabled") uid = str(uuid.uuid4()) payload = { "iss": f"{config.ISSUER}/app/{client_app.app_id}", "sub": email, "uid": uid, } token = jwt.generate_jwt( payload, client_app.get_refresh_key(), "ES256", datetime.timedelta(hours=client_app.refresh_token_expire_hours), ) token_hash = PWD_CONTEXT.hash(token) expires = datetime.datetime.now() + datetime.timedelta( hours=client_app.refresh_token_expire_hours) await RefreshToken( app_id=client_app.app_id, email=email, hash=token_hash, expires=expires, uid=uid, ).insert() return token
def gen_client_token(): claims = {'scope': ['web-app'], 'client_id': 'internal'} try: jwt = python_jwt.generate_jwt(claims, priv_key=jwk.JWK.from_pem( g.config.private_key), algorithm='RS256', lifetime=datetime.timedelta(seconds=300), jti_size=16) except: return None try: jwt_decoded = python_jwt.verify_jwt(jwt, pub_key=jwk.JWK.from_pem( g.config.public_key), allowed_algs=['RS256'], checks_optional=True, ignore_not_implemented=True) except: return None result = { 'access_token': jwt, 'token_type': 'bearer', 'scope': 'web-app', "iat": jwt_decoded[1].get('iat'), 'expires_in': jwt_decoded[1].get('exp') - jwt_decoded[1].get('iat') - 1, "jti": jwt_decoded[1].get('jti') } return result
def create_custom_token(uid, is_premium_account): service_account_email = app_identity.get_service_account_name() payload = { 'iss': service_account_email, 'sub': service_account_email, 'aud': 'https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit', 'uid': uid, 'claims': { 'premium_account': is_premium_account } } exp = datetime.timedelta(minutes=60) token = jwt.generate_jwt(payload, None, 'RS256', exp) header, body, secret = token.split('.') # 返ってくるヘッダーは 'alg': 'none' になっているので RS256 に変更 header = jws.utils.encode({ 'typ': 'JWT', 'alg': 'RS256' }).decode('utf-8') # app_identity.sign_blob を使ってサインを作成 sign = base64.urlsafe_b64encode(app_identity.sign_blob(str(header + '.' + body))[1]).strip('=') return header + '.' + body + '.' + sign
def generate(email: str, client_app: ClientApp) -> str: payload = {"iss": f"{config.ISSUER}/app/{client_app.app_id}", "sub": email} return jwt.generate_jwt( payload, client_app.get_key(), "ES256", datetime.timedelta(minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES), )
def create_tmp_token(key_path, server_id): with open(key_path, "rb") as _file: key = _file.read() private_key = jwk.JWK.from_pem(key) payload = {"iss": server_id} token = jwt.generate_jwt(payload, private_key, 'RS256', datetime.timedelta(minutes=5)) return token return None
def make_bench_verify_token(alg): """ Return function which will generate token for particular algorithm """ privk = priv_keys[alg].get('default', priv_key) token = jwt.generate_jwt(payload, privk, alg, timedelta(days=1)) def f(_): """ Verify token """ pubk = pub_keys[alg].get('default', pub_key) jwt.verify_jwt(token, pubk, [alg]) return f
def create_tmp_token(): with open(PRIVATE_KEY_PATH, "rb") as _file: key = _file.read() private_key = jwk.JWK.from_pem(key) payload = {"iss": SERVER_ID} my_token = jwt.generate_jwt(payload, private_key, 'RS256', datetime.timedelta(minutes=5)) return my_token return None
def get_jwt(self, payload): """ this medthod create a token with python_jwt """ assert isinstance(payload, dict) assert('id' in payload) self.require_setting("cookie_secret", "crypto jwt") expire_days = self.settings.get("max_age_days", 1) return jwt.generate_jwt(payload, self.settings['cookie_secret'], "HS256", datetime.timedelta(days=expire_days))
def create_access_token(user_name, password): return \ JWT._set_access_token( access_token=jwt.generate_jwt( claims={'user_name': user_name, 'password': password}, priv_key=JWT._get_private_key(), algorithm='PS256', lifetime=timedelta(minutes=5) ), user_name=user_name)
def test_will_raise_exception_when_typ_is_not_Bearer(): payload = {'typ': 'ID', 'foo': 'bar', 'baz': 42} other_headers = {'kid': key.key_id} token = generate_jwt(payload, key, 'RS256', datetime.timedelta(minutes=5), other_headers=other_headers) assert_raises(Exception, verify_jwt(token, key, ['RS256']))
def sign(self, data, ttl=None): # TODO: handle error conditions # TODO: maybe croak if self.key is None ttl = ttl or self.ttl payload = {'data': data} token = jwt.generate_jwt(payload, priv_key=self.key, algorithm='RS256', lifetime=ttl) return token
def post(self, request): username = request.POST.get('username', None) password = request.POST.get('password', None) user = authenticate(request, username=username, password=password) if user is not None: payload = {'user': username} token = jwt.generate_jwt(payload, key, alg, datetime.timedelta(days=7)) # 生成JWT logger.info('登陆成功: {}'.format(username)) return JsonResponse({'status': 200, 'message': '登陆成功', 'token': token, 'user': username}) else: logger.error('登陆失败: {}'.format(username)) return JsonResponse({'status': 500, 'message': '登陆失败'})
def set_token(payload): f1 = open('apps/login/pem/PRIV.pem', 'rb') PRIV_PEM = f1.read() PRIV_KEY = jwk.JWK.from_pem(PRIV_PEM) # 私密秘钥 f1.close() if not isinstance(payload, dict): return None token = jwt.generate_jwt(payload, priv_key=PRIV_KEY, algorithm='RS256', lifetime=datetime.timedelta(hours=LIFE_TIME)) return token
def test_verify_wrong_key_fails(fake_email, fake_client_app): key = jwk.JWK.generate(kty="EC", size=2048) payload = {"iss": f"{config.ISSUER}/12345", "sub": fake_email} token = jwt.generate_jwt( payload, key, "ES256", datetime.timedelta(minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES), ) with pytest.raises(security_token.TokenVerificationError): security_token.verify(token, fake_client_app)
def test_verify_wrong_issuer_app_id_fails(fake_email, fake_client_app): payload = {"iss": f"{config.ISSUER}/{uuid.uuid4()}", "sub": fake_email} # key = jwk.JWK(**fake_client_app.key) token = jwt.generate_jwt( payload, fake_client_app.get_key(), "ES256", datetime.timedelta(seconds=1), ) with pytest.raises(security_token.TokenVerificationError): security_token.verify(token, fake_client_app)
def run(): key_uri = os.path.join(BASE_DIR, 'afinidata.key') key_file = pem.parse_file(key_uri) key_string = str(key_file[0]).encode() payload = {'foo': 'bar', 'wup': 90} priv_key = jwk.JWK.from_pem(key_string) token = jwt.generate_jwt(payload, priv_key, 'RS256', datetime.timedelta(minutes=1)) print('token: ', token) header, claims = jwt.verify_jwt(token, priv_key, ['RS256']) print(header, claims) for k in payload: assert claims[k] == payload[k]
def create_custom_token(self, uid, additional_claims=None): service_account_email = self.credentials.service_account_email private_key = RSA.importKey(self.credentials._private_key_pkcs8_pem) payload = { "iss": service_account_email, "sub": service_account_email, "aud": "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit", "uid": uid } if additional_claims: payload["claims"] = additional_claims exp = datetime.timedelta(minutes=60) return jwt.generate_jwt(payload, private_key, "RS256", exp)
def generate(): auth_code = request.args.get("code") print(auth_code) auth_code_lib = ["apigwcode", "serverlesscode"] if auth_code in auth_code_lib: priv_pem = str(get_file_content('priv_pem')).encode('utf-8') payload = {'foo': 'bar', 'wup': 90} priv_key = jwk.JWK.from_pem(priv_pem) token = jwt.generate_jwt(claims=payload, priv_key=priv_key, algorithm='RS256', lifetime=datetime.timedelta(minutes=5)) return token else: return "invalid"
def generate_jwt_token(private_pem: bytes, app_id: int) -> str: """Generates a JWT token valid for 10 minutes using the private key. Args: private_pem: the private key that is used to generate a JWT app_id the Application id Returns: The JWT that was generated using the private key and the app id """ private_key = jwcrypto.jwk.JWK.from_pem(private_pem) payload = {"iss": app_id} duration = datetime.timedelta(minutes=10) return python_jwt.generate_jwt(payload, private_key, "RS256", duration)
def test_exported_key_cannot_sign_keys(fake_client_app, fake_email): exported_key_dict = security_client_app.export_public_key(fake_client_app) exported_key = jwk.JWK(**exported_key_dict) payload = {"iss": f"{config.ISSUER}/12345", "sub": fake_email} token = None with pytest.raises(TypeError): token = jwt.generate_jwt( payload, exported_key, "ES256", datetime.timedelta(minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES), ) assert token is None
def issue_token(self, permissions, minutes=60, hours=0, days=0): payload = { 'iss': os.environ['ISSUER'], 'sub': os.environ['SUBJECT'], 'aud': os.environ['AUDIENCE'], 'permissions': permissions } with open(f"{os.environ['KEY_PATH']}/{os.environ['KEY_NAME']}.key", 'r') as key_path: private_key = key_path.readline() return jwt.generate_jwt( payload, jwk.JWK.from_json(private_key), 'RS256', datetime.timedelta(minutes=minutes, hours=hours, days=days))