This is my login authentication API.
def login():
if request.method == 'OPTIONS':
return jsonify({'message': 'CORS preflight successful'}), 200
data = request.json
email = data.get('email')
password = data.get('password')
print("Login data:", data)
user = SystemUser.query.filter_by(email_id=email).first()
print("User found:", user)
if user:
userPass = user.password
print(f"DB Password: {userPass} ({type(userPass)}), Entered Password: {password} ({type(password)})")
if userPass == password:
print("Login successful!!!")
session.permanent = True
session['user'] = {
'email': user.email_id,
'name': user.employee_name,
'group_code': user.group_code,
'school_code': user.school_code,
'status': user.status,
}
return jsonify({
'message': 'Login successful',
'success': True,
'user': session['user'],
}), 200
return jsonify({'message': 'Invalid credentials'}), 401
login.jsx Here user data has been saved to sessionStorage.
const handleLogin = async (e) => {
e.preventDefault(); // Prevent form default behavior (page reload)
try {
const response = await axios.post(
"http://127.0.0.1:5000/api/auth/login",
{
email,
password,
},
{
withCredentials: true,
headers: {
"Content-Type": "application/json",
},
}
);
if (response.data.success) {
console.log("Login successful:", response.data);
const userString = JSON.stringify(response.data.user);
setUserData(userString); // Optional: set state for use in app
sessionStorage.setItem("user", userString); // Optional: store in browser sessionStorage
setIsAuthenticated(true);
navigate("/dashboard");
}
This works fine.
But I can't do so on a different route or service when I want to access or use the user's data.
routes.py
@schoolPrivilegeBP.route("/assignPrivileges", methods=["POST"])
@cross_origin(supports_credentials=True)
def assignPrivilegesSchoolWiseRoute():
user = session.get('user')
print("Session user from assignPrivilegesSchoolWiseRoute:", user)
It returns "None"
Here is my app.py:
app.config['SESSION_TYPE'] = 'filesystem'
app.config['SESSION_PERMANENT'] = False
app.config['SESSION_USE_SIGNER'] = True
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
app.config['SESSION_COOKIE_SECURE'] = False
app.config['SESSION_FILE_DIR'] = './flask_sessions'
app.permanent_session_lifetime = timedelta(days=1)
CORS(app, resources={r"/*": {"origins": http://localhost:5173"}},supports_credentials=True)
Also in the flask_sessions, I can see the session has been created as per the login credentials.
You can define a proxy if you expect that both the frontend and backend will be hosted behind the same server. In this case, add the following line to the package.json
file. This also resolves potential CORS issues, as requests to the React server will be forwarded to the Flask backend in the background if necessary.
"proxy": "http://localhost:5000"
However, if your requirements are different, you can use third-party cookies. To do so, change the definition in your backend as follows.
app.config["SESSION_COOKIE_SAMESITE"]="None"
app.config["SESSION_COOKIE_SECURE"]=True