I
I
ilyaux2020-11-26 15:03:42
Flask
ilyaux, 2020-11-26 15:03:42

How to make a private get/post request in flask?

After authorization, I get a session token and so that the user can continue to work with the rest, I want to use requests of this format:

localhost/{ token}/profile

How to properly implement such a rest in flask?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Yakushenko, 2020-11-26
@kshnkvn

Tokens should be sent from the client in headers, and validation for routes should be used on the server, for example with flask-jwt-
extended

from flask import Flask, request, jsonify
from flask_jwt_extended import (
    JWTManager,
    create_access_token,
    jwt_required,
    get_jwt_identity
)

app = Flask(__name__)

app.config['SECRET_KEY'] = 'super-secret'
app.config['JWT_SECRET_KEY'] = app.config['SECRET_KEY']
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = False

jwt = JWTManager(app)

users = ['kshnkvn']


@app.route('/login', methods=['POST'])
def login():
    user = request.json.get('user')

    if user not in users:
        return jsonify(
            {'status': False, 'result': 'User not exists'})
    else:
        return jsonify(
            {'status': True, 'result': create_access_token(identity=user)})


@app.route('/user', methods=['GET'])
@jwt_required
def user():
    user = get_jwt_identity()
    return jsonify({'status': True, 'result': user})


if __name__ == '__main__':
    app.run(debug=True, port=6061)

As a result, if we send a request /userwithout a header with authorization, then we get in response:
{
    "msg": "Missing Authorization Header"
}

To get a token, we send POSTa request to /loginwhere in the request body we send JSONwith the username, and in response we get a token:
{
    "status": true,
    "result": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2MDYzOTk0NjcsIm5iZiI6MTYwNjM5OTQ2NywianRpIjoiMTgxZmY2ZGQtN2FmNS00ZTUxLTlhMzAtODA3MTNhYzNlZGJlIiwiaWRlbnRpdHkiOiJrc2hua3ZuIiwiZnJlc2giOmZhbHNlLCJ0eXBlIjoiYWNjZXNzIn0.DwzxBd-6Hz1Gg6O-7JIoFrBm_XzCoiOD6xIRhFUjG0Q"
}

After that, we add a header to each request
"Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2MDYzOTk0NjcsIm5iZiI6MTYwNjM5OTQ2NywianRpIjoiMTgxZmY2ZGQtN2FmNS00ZTUxLTlhMzAtODA3MTNhYzNlZGJlIiwiaWRlbnRpdHkiOiJrc2hua3ZuIiwiZnJlc2giOmZhbHNlLCJ0eXBlIjoiYWNjZXNzIn0.DwzxBd-6Hz1Gg6O-7JIoFrBm_XzCoiOD6xIRhFUjG0Q"
and go to the desired link, for example, for the /userfollowing answer:
{
    "status": true,
    "result": "kshnkvn"
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question