Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23305

the token is not being validated to return information

$
0
0
The /login route gives me the token, but when I go to the /userinfo route and send the token it gives me an invalid tokendef auth():    cursor = conexao.cursor()    if verifica():        token = jwt.encode({'nome': request.json['username'],'exp': str(datetime.now(timezone.utc) + timedelta(seconds=120))        }, app.config['SECRET_KEY'], algorithm="HS256")        cursor.close()        return jsonify({'token': token})    else:        cursor.close()        return make_response('Credenciais inválidas', 403)def verifica():    nome = request.json['username']    senha = request.json['password_hash']    cursor = conexao.cursor()    comando = f'SELECT username, password_hash FROM users WHERE username = "{nome}"'    cursor.execute(comando)    resultado = cursor.fetchall()    for row in resultado:        username, hashed_senha = row        if descripto(senha, hashed_senha.encode('utf-8')):            cursor.close()            return True    cursor.close()    return Falsedef token_request(func):    @wraps(func)    def decorated(*args, **kwargs):        token = request.args.get('token')        if not token:            return jsonify({'Alerta': 'Token não recebido'}), 403        try:            payload = jwt.decode(token, app.config['SECRET_KEY'], algorithms=["HS256"])        except jwt.ExpiredSignatureError:            return jsonify({'Alerta': 'Token expirado'}), 403        except jwt.InvalidTokenError:            return jsonify({'Alerta': 'Token inválido'}), 403        return func(payload, *args, **kwargs)    return decorated@app.route('/login', methods=['POST'])def login_auth():    cursor = conexao.cursor()    if verifica():        token = jwt.encode({'nome': request.json['username'],'exp': str(datetime.now(timezone.utc) + timedelta(seconds=120))        }, app.config['SECRET_KEY'], algorithm="HS256")        cursor.close()        return jsonify({'token': token})    else:        cursor.close()        return make_response('Impossível verificar', 403)@app.route('/userinfo', methods=['GET'])@token_requestdef user_info(payload):    username = payload['nome']    cursor = conexao.cursor()    comando = f'SELECT username, email FROM users WHERE username = "{username}"'    cursor.execute(comando)    resultado = cursor.fetchone()    cursor.close()    if resultado:        username, email = resultado        return jsonify({"username": username, "email": email}), 200    else:        return jsonify({"message": "Usuário não encontrado"}), 404

The /login route gives me the token, but when I go to the /userinfo route and send the token, it gives me an invalid token and so I can't access the user's information. Here is the code with the login routes that return a token when sending a username and password, and the authentication route that returns the user's personal information when sending the token. I can receive the token from the login route, but I can't authenticate it.


Viewing all articles
Browse latest Browse all 23305

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>