Answer the question
In order to leave comments, you need to log in
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
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)
/user
without a header with authorization, then we get in response:{
"msg": "Missing Authorization Header"
}
POST
a request to /login
where in the request body we send JSON
with the username, and in response we get a token:{
"status": true,
"result": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2MDYzOTk0NjcsIm5iZiI6MTYwNjM5OTQ2NywianRpIjoiMTgxZmY2ZGQtN2FmNS00ZTUxLTlhMzAtODA3MTNhYzNlZGJlIiwiaWRlbnRpdHkiOiJrc2hua3ZuIiwiZnJlc2giOmZhbHNlLCJ0eXBlIjoiYWNjZXNzIn0.DwzxBd-6Hz1Gg6O-7JIoFrBm_XzCoiOD6xIRhFUjG0Q"
}
"Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2MDYzOTk0NjcsIm5iZiI6MTYwNjM5OTQ2NywianRpIjoiMTgxZmY2ZGQtN2FmNS00ZTUxLTlhMzAtODA3MTNhYzNlZGJlIiwiaWRlbnRpdHkiOiJrc2hua3ZuIiwiZnJlc2giOmZhbHNlLCJ0eXBlIjoiYWNjZXNzIn0.DwzxBd-6Hz1Gg6O-7JIoFrBm_XzCoiOD6xIRhFUjG0Q"
and go to the desired link, for example, for the /user
following answer:{
"status": true,
"result": "kshnkvn"
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question