I'm still in doubt even after 5 days of coding and studying about how to redirect a route not protected by jwt_required to one that is. I know it requires using authorization, but I'm unsure how to implement that on the backend. I only have a notion of how to return jsonify in the body with an access_token for the frontend to handle, but I have no knowledge of frontend and whether the redirection should be done there. I'm completely lost.
Additionally, I've attempted to achieve this on the frontend using fetch with headers containing authorization, however, I consistently encounter a 401 error. How should I proceed?
from flask import Flask, render_template, request, jsonify, redirect, url_for
from flask_jwt_extended import JWTManager, jwt_required, create_access_token
import requests
app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = 'super-secret'
jwt = JWTManager(app)
users = {
"username": "password"
}
@app.route('/', methods=["POST", "GET"])
def home():
if request.method == "POST":
username = request.form.get('username')
password = request.form.get('password')
if username in users and users[username] == password:
access_token = create_access_token(identity=username)
return redirect(url_for('protected'), access_token=access_token)
else:
return jsonify({"error": "Invalid username or password"}), 401
return render_template('login.html')
@app.route('/protected', methods = ['GET', 'POST'])
@jwt_required()
def protected():
return render_template('protected.html')
if __name__ == '__main__':
app.run(debug=True)
Login.hmtl:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
</head>
<body>
<h2>Login</h2>
<form id="loginForm", method="POST">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username" placeholder="username"><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br><br>
<button type="submit">Login</button>
</form>
</body>
</html>
protected_html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Protected</title>
</head>
<body>
<h2>Protected Page</h2>
<p>This page is protected. Only accessible with a valid token.</p>
</body>
</html>
I've attempted to achieve this on the frontend using fetch with headers containing authorization, however, I consistently encounter a 401 error
and I expected that the fetch with redirect the window to the protected route and I can see the route