Fullstack Python: Building a REST API with Flask and React for Authentication
Building a full-stack application requires a seamless interaction between the backend and frontend to ensure a smooth user experience. In this guide, we'll explore how to create a secure authentication system using Flask for the backend and React for the frontend. By leveraging JSON Web Tokens (JWT), we’ll establish secure user authentication, enabling protected API access.
Step 1: Setting Up Flask for the Backend
Flask is a lightweight Python framework ideal for building RESTful APIs. Start by installing the required libraries:
bash
pip install flask flask-cors flask-bcrypt flask-jwt-extended
Initializing the Flask App
Create a simple Flask server in app.py:
python
from flask import Flask, request, jsonify
from flask_cors import CORS
from flask_bcrypt import Bcrypt
from flask_jwt_extended import JWTManager, create_access_token, jwt_required
app = Flask(__name__)
app.config["JWT_SECRET_KEY"] = "your_secret_key"
CORS(app)
bcrypt = Bcrypt(app)
jwt = JWTManager(app)
users = {}
@app.route("/register", methods=["POST"])
def register():
data = request.get_json()
hashed_pw = bcrypt.generate_password_hash(data["password"]).decode("utf-8")
users[data["username"]] = hashed_pw
return jsonify({"message": "User registered successfully"})
@app.route("/login", methods=["POST"])
def login():
data = request.get_json()
stored_pw = users.get(data["username"])
if stored_pw and bcrypt.check_password_hash(stored_pw, data["password"]):
token = create_access_token(identity={"username": data["username"]})
return jsonify({"access_token": token})
return jsonify({"error": "Invalid credentials"}), 401
if __name__ == "__main__":
app.run(debug=True)
This setup includes user registration and login authentication using JWT tokens.
Step 2: Building the React Frontend
Create a React application and install required dependencies:
bash
npx create-react-app my-app
cd my-app
npm install axios react-router-dom
Creating a Login Component
Inside Login.js, define the login form and handle authentication:
javascript
import React, { useState } from "react";
import axios from "axios";
const Login = () => {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const handleLogin = async () => {
try {
const response = await axios.post("http://localhost:5000/login", {
username,
password,
});
localStorage.setItem("token", response.data.access_token);
alert("Login successful!");
} catch (error) {
alert("Invalid credentials");
}
};
return (
<div>
<input type="text" placeholder="Username" onChange={(e) => setUsername(e.target.value)} />
<input type="password" placeholder="Password" onChange={(e) => setPassword(e.target.value)} />
<button onClick={handleLogin}>Login</button>
</div>
);
};
export default Login;
Step 3: Protecting Routes with JWT Authentication
Secure API Access in Flask
We can create protected routes in Flask that require authentication using JWT:
python
@app.route("/dashboard", methods=["GET"])
@jwt_required()
def dashboard():
return jsonify({"message": "Welcome to the protected dashboard!"})
Step 4: Handling Protected Routes in React
Use React Router to restrict access to certain pages:
javascript
import { BrowserRouter as Router, Route, Navigate } from "react-router-dom";
const PrivateRoute = ({ children }) => {
return localStorage.getItem("token") ? children : <Navigate to="/login" />;
};
<Router>
<Route path="/dashboard" element={<PrivateRoute><Dashboard /></PrivateRoute>} />
</Router>
With this setup, only logged-in users can access the protected Dashboard route.
Final Thoughts
This Flask-React authentication system provides a secure and scalable solution for user login and route protection. By leveraging JWT tokens, Flask ensures that only authorized users access protected APIs, while React handles the authentication flow seamlessly.
Would you like to explore additional enhancements, such as database integration or OAuth-based authentication? Let’s dive deeper!
Learn FullStack Python Training
Read More : Flask and Flask-SocketIO: Implementing Real-Time WebSockets for Fullstack Applications
Visit Our IHUB Talent Training Institute in Hyderabad
Get Direction
Comments
Post a Comment