Flask REST API with JWT and Google OAuth
Spanish version
This is a REST API built with Flask that implements two authentication methods:
- JWT Authentication: Traditional login and registration with username/password
- OAuth 2.0 Authentication: Google login
📋 Prerequisites
- Python 3.8 or higher
- pip (Python package manager)
- Google account with OAuth 2.0 configured
🚀 Installation
- Create a virtual environment (recommended)
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
Or use miniconda
conda create -n environment_name python=3.10
pip install -r requirements.txt
# To save list of packages
# pip freeze > requirements.txt
- Install dependencies
pip install -r requirements.txt
- Configure environment variables
Create a .env file in the project root with the following content:
SECRET_KEY=your-secret-key-here-change-in-production
JWT_SECRET_KEY=your-jwt-secret-here-change-in-production
DATABASE_URL=sqlite:///app.db
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
CORS_ORIGINS=http://localhost:3000
Configure Google OAuth 2.0
- Go to Google Cloud Console
- Create a new project or select an existing one
- Enable Google+ API
- Go to "Credentials" > "Create credentials" > "OAuth 2.0 Client ID"
- Configure:
- Application type: Web application
- Authorized redirect URIs:
http://localhost:5000/authorize/google
- Copy the Client ID and Client Secret to your
.env file
Create Google Console Project and enable Google+ API
- If only using docker for MySQL or PostgreSQL database
Use Docker
# Commands to use MySQL container
docker run --name mymysql -e MYSQL_ROOT_PASSWORD=mypassword -p 3306:3306 -d mysql:latest
docker exec -it mymysql bash
# Inside the MySQL container
mysql -u root -p
create database flaskmysql;
And your .env DATABASE_URL will be:
# PostgreSQL example
DATABASE_URL=postgresql://postgres:mypassword@localhost:5432/flaskpostgresql
# MySQL example
DATABASE_URL=mysql+pymysql://root:mypassword@localhost:3306/flaskmysql
🏃 Run the Application
python database.py
The API will be available at http://localhost:5000
📚 API Endpoints
JWT Authentication
POST /api/register
Register a new user.
Request Body:
{
"username": "user@example.com",
"password": "password123"
}
Response (201):
{
"message": "User registered successfully",
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGc...",
"user": {
"id": 1,
"username": "user@example.com"
}
}
POST /api/login
Login with username and password.
Request Body:
{
"username": "user@example.com",
"password": "password123"
}
Response (200):
{
"message": "Login successful",
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGc...",
"user": {
"id": 1,
"username": "user@example.com"
}
}
Google OAuth Authentication
GET /api/login/google
Initiates Google authentication. Redirects user to Google for authorization.
GET /api/authorize/google
Google OAuth callback. Redirects to frontend with JWT token.
Protected Routes
GET /api/protected
Protected route that requires a valid JWT token.
Headers:
Authorization: Bearer <token>
Response (200):
{
"message": "Authorized access",
"user": {
"id": 1,
"username": "user@example.com"
}
}
GET /api/user/profile
Gets the authenticated user's profile.
Headers:
Authorization: Bearer <token>
Response (200):
{
"user": {
"id": 1,
"username": "user@example.com"
}
}
Utilities
GET /api/health
Verifies that the API is running.
Response (200):
{
"status": "ok",
"message": "Flask API running correctly"
}
🔒 Using the JWT Token
After authenticating (login or Google), you'll receive an access_token. To access protected routes, include this token in the Authorization header:
Authorization: Bearer <access_token>
The token expires after 1 hour (3600 seconds). You can modify this in config.py.
🛠️ Project Structure
/
├── database.py # Main Flask application with all routes
├── config.py # Application configuration
├── requirements.txt # Project dependencies
└── .env # Environment variables (not included in git)
📝 Notes
- The database is created automatically when the application runs
- Users authenticated with Google don't have a password (
password_hash = None)
- The JWT token is stored in the frontend (localStorage) and sent with each request
- CORS is configured to allow requests from
http://localhost:3000 (Next.js)
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
👨💻 Author
Diego Ivan Perea Montealegre
Created by Diego Ivan Perea Montealegre
Spanish
API REST Flask con JWT y OAuth de Google
Esta es una API REST construida con Flask que implementa dos métodos de autenticación:
- Autenticación JWT: Login y registro tradicional con username/password
- Autenticación OAuth 2.0: Login con Google
📋 Requisitos Previos
- Python 3.8 o superior
- pip (gestor de paquetes de Python)
- Cuenta de Google con OAuth 2.0 configurado
🚀 Instalación
- Crear un entorno virtual (recomendado)
python -m venv venv
source venv/bin/activate # En Windows: venv\Scripts\activate
o usar miniconda
conda create -n environment_name python=3.10
pip install -r requirements.txt
# for save list of packages
# pip freeze > requirements.txt
- Instalar dependencias
pip install -r requirements.txt
- Configurar variables de entorno
Crea un archivo .env en la raíz del proyecto con el siguiente contenido:
SECRET_KEY=tu-clave-secreta-aqui-cambiar-en-produccion
JWT_SECRET_KEY=tu-jwt-secreta-aqui-cambiar-en-produccion
DATABASE_URL=sqlite:///app.db
GOOGLE_CLIENT_ID=tu-google-client-id
GOOGLE_CLIENT_SECRET=tu-google-client-secret
CORS_ORIGINS=http://localhost:3000
Configurar Google OAuth 2.0
- Ve a Google Cloud Console
- Crea un nuevo proyecto o selecciona uno existente
- Habilita la API de Google+
- Ve a "Credenciales" > "Crear credenciales" > "ID de cliente OAuth 2.0"
- Configura:
- Tipo de aplicación: Aplicación web
- URI de redirección autorizados:
http://localhost:5000/authorize/google
- Copia el Client ID y Client Secret a tu archivo
.env
Create Google Console Project and enable Google+ API
- if only use docker for db mysql or postgresql
Use Docker
#Comands for use docker container mysql
docker run --name mymysql -e MYSQL_ROOT_PASSWORD=mypassword -p 3306:3306 -d mysql:latest
docker exec -it mymysql bash
#Inside of the container mysql
mysql -u root -p
create database flaskmysql;
And your .env in DATABASE_URL wiil be
# posgresql example
DATABASE_URL= postgresql://postgres:mypassword@localhost:5432/flaskpostgresql
# mysql example
DATABASE_URL=mysql+pymysql://root:mypassword@localhost:3306/flaskmysql
🏃 Ejecutar la aplicación
python database.py
La API estará disponible en http://localhost:5000
📚 Endpoints de la API
Autenticación JWT
POST /api/register
Registra un nuevo usuario.
Request Body:
{
"username": "usuario@ejemplo.com",
"password": "contraseña123"
}
Response (201):
{
"message": "Usuario registrado exitosamente",
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGc...",
"user": {
"id": 1,
"username": "usuario@ejemplo.com"
}
}
POST /api/login
Inicia sesión con username y password.
Request Body:
{
"username": "usuario@ejemplo.com",
"password": "contraseña123"
}
Response (200):
{
"message": "Login exitoso",
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGc...",
"user": {
"id": 1,
"username": "usuario@ejemplo.com"
}
}
Autenticación Google OAuth
GET /api/login/google
Inicia el proceso de autenticación con Google. Redirige al usuario a Google para autorización.
GET /api/authorize/google
Callback de Google OAuth. Redirige al frontend con el token JWT.
Rutas Protegidas
GET /api/protected
Ruta protegida que requiere un token JWT válido.
Headers:
Authorization: Bearer <token>
Response (200):
{
"message": "Acceso autorizado",
"user": {
"id": 1,
"username": "usuario@ejemplo.com"
}
}
GET /api/user/profile
Obtiene el perfil del usuario autenticado.
Headers:
Authorization: Bearer <token>
Response (200):
{
"user": {
"id": 1,
"username": "usuario@ejemplo.com"
}
}
Utilidades
GET /api/health
Verifica que la API está funcionando.
Response (200):
{
"status": "ok",
"message": "API Flask funcionando correctamente"
}
🔒 Uso del Token JWT
Después de autenticarte (login o Google), recibirás un access_token. Para acceder a rutas protegidas, incluye este token en el header Authorization:
Authorization: Bearer <access_token>
El token expira después de 1 hora (3600 segundos). Puedes modificar esto en config.py.
🛠️ Estructura del Proyecto
/
├── database.py # Aplicación Flask principal con todas las rutas
├── config.py # Configuración de la aplicación
├── requirements.txt # Dependencias del proyecto
└── .env # Variables de entorno (no incluido en git)
📝 Notas
- La base de datos se crea automáticamente al ejecutar la aplicación
- Los usuarios autenticados con Google no tienen contraseña (
password_hash = None)
- El token JWT se almacena en el frontend (localStorage) y se envía en cada petición
- CORS está configurado para permitir peticiones desde
http://localhost:3000 (Next.js)
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
👨💻 Author / Autor
Diego Ivan Perea Montealegre
Created by Diego Ivan Perea Montealegre