Skip to content

rishika3895/message-app

Repository files navigation

Spring Boot Message App with Google OAuth2 & Cloud Run

Java Spring Boot Google Cloud Firestore

A modern Spring Boot REST API with Google OAuth2 authentication and comprehensive post management features, designed for seamless deployment on Google Cloud Run.

🚀 Features

🔐 Authentication & Security

  • Google OAuth2 Integration: Secure authentication using Google accounts
  • JWT Token Management: Stateless authentication with JSON Web Tokens
  • User Authorization: Users can only modify/delete their own posts
  • Spring Security: Comprehensive security configuration with CORS support

📝 Post Management

  • Full CRUD Operations: Create, Read, Update, Delete posts
  • Rich Post Model: Posts include subject, body, author, and timestamps
  • Ownership Validation: Users can only edit their own content
  • RESTful API: Clean REST endpoints following best practices

☁️ Cloud-Native Features

  • Google Cloud Firestore: NoSQL document database for scalability
  • Google Cloud Run: Serverless container deployment
  • Google Cloud Build: Automated CI/CD pipeline
  • Artifact Registry: Secure container image storage
  • Health Checks: Built-in monitoring and health endpoints

🛠️ Technology Stack

Component Technology
Backend Framework Spring Boot 3.x
Security Spring Security + OAuth2
Database Google Cloud Firestore
Authentication Google OAuth2 + JWT
Containerization Docker
Cloud Platform Google Cloud Run
Build Tool Maven
Java Version 17 LTS

📚 API Documentation

Authentication Endpoints

Method Endpoint Description Auth Required
POST /auth/google Authenticate with Google OAuth2 token No

Post Management Endpoints

Method Endpoint Description Auth Required
GET /api/posts Retrieve all posts Yes
GET /api/posts/{id} Get specific post by ID Yes
POST /api/posts Create new post Yes
PUT /api/posts/{id} Update existing post (owner only) Yes
DELETE /api/posts/{id} Delete post (owner only) Yes

System Endpoints

Method Endpoint Description Auth Required
GET /health Application health status No

🚀 Quick Start

Prerequisites

  • ☕ Java 17 or higher
  • 📦 Maven 3.6+
  • ☁️ Google Cloud SDK
  • 🐳 Docker (for containerization)
  • 🔑 Google Cloud Project with billing enabled

🏠 Local Development Setup

  1. Clone and Setup

    git clone https://github.com/yourusername/message-app.git
    cd message-app
  2. Install Firebase Tools & Start Emulator

    npm install -g firebase-tools
    firebase login
    firebase emulators:start --only firestore
  3. Run Application Locally

    mvn spring-boot:run -Dspring-boot.run.profiles=local

    The application will be available at http://localhost:8080

☁️ Google Cloud Deployment

  1. Setup Google Cloud

    # Authenticate and set project
    gcloud auth login
    gcloud config set project YOUR_PROJECT_ID
    
    # Enable required services
    gcloud services enable run.googleapis.com
    gcloud services enable cloudbuild.googleapis.com
    gcloud services enable artifactregistry.googleapis.com
    gcloud services enable firestore.googleapis.com
  2. Create Artifact Registry Repository

    gcloud artifacts repositories create message-app-repo \
      --repository-format=docker \
      --location=europe-west1
  3. Deploy to Cloud Run

    chmod +x deploy-cloud-run.sh
    ./deploy-cloud-run.sh

⚙️ Configuration Profiles

The application supports multiple environment-specific configurations:

Profile Purpose Security Database
local Local development Minimal Firestore Emulator
simple Cloud Run minimal Basic JWT Firestore Disabled
nosecurity Testing only Disabled Firestore Disabled
public Public demo Minimal Firestore Disabled

🔧 Environment Variables

Required for Production

GOOGLE_CLOUD_PROJECT=your-project-id
messageapp.app.jwtSecret=your-jwt-secret-key
messageapp.app.jwtExpirationMs=86400000

Optional Configuration

PORT=8080
SPRING_PROFILES_ACTIVE=simple

📁 Project Structure

message-app/
├── 📁 src/main/java/com/example/messageapp/
│   ├── 🚀 MessageAppApplication.java
│   ├── 📁 config/
│   │   ├── 🔒 SecurityConfig.java
│   │   └── 🔥 FirestoreConfig.java
│   ├── 📁 controller/
│   │   ├── 🔐 AuthController.java
│   │   └── 📝 PostController.java
│   ├── 📁 dto/
│   │   ├── 📥 PostRequestDto.java
│   │   └── 📤 PostResponseDto.java
│   ├── 📁 entity/
│   │   └── 📄 Post.java
│   ├── 📁 repository/
│   │   └── 🗄️ PostRepository.java
│   ├── 📁 service/
│   │   └── 🔧 PostService.java
│   └── 📁 util/
│       └── 🎫 JwtUtils.java
├── 📁 src/main/resources/
│   ├── ⚙️ application*.properties
│   └── 🔥 firebase.json
├── 🐳 Dockerfile
├── 🚀 deploy-cloud-run.sh
└── 📖 README.md

🔐 Security Implementation

Authentication Flow

sequenceDiagram
    participant Client
    participant Backend
    participant Google
    
    Client->>Google: 1. OAuth2 Login
    Google->>Client: 2. ID Token
    Client->>Backend: 3. POST /auth/google (ID Token)
    Backend->>Google: 4. Validate Token
    Google->>Backend: 5. User Info
    Backend->>Client: 6. JWT Token
    Client->>Backend: 7. API Calls (JWT in Header)
Loading

Authorization Rules

  • 🔒 All API endpoints require valid JWT (except /auth/google and /health)
  • 👤 Posts are tied to authenticated user's email
  • ✅ Users can only update/delete their own posts
  • 🛡️ CORS configured for cross-origin requests

🧪 Testing the API

Using Google Cloud Shell

# Get access token
TOKEN=$(gcloud auth print-access-token)
SERVICE_URL="https://your-service-url"

# Test health endpoint
curl -H "Authorization: Bearer $TOKEN" \
     -w "\nStatus: %{http_code}\n" \
     "$SERVICE_URL/health"

# Get all posts
curl -H "Authorization: Bearer $TOKEN" \
     -H "Content-Type: application/json" \
     -w "\nStatus: %{http_code}\n" \
     "$SERVICE_URL/api/posts"

# Create a new post
curl -X POST \
     -H "Authorization: Bearer $TOKEN" \
     -H "Content-Type: application/json" \
     -d '{"subject":"Hello World","body":"My first post!"}' \
     -w "\nStatus: %{http_code}\n" \
     "$SERVICE_URL/api/posts"

Using Postman or curl

# Example POST request body
{
  "subject": "My Post Title",
  "body": "This is the content of my post"
}

# Headers required
Authorization: Bearer YOUR_JWT_TOKEN
Content-Type: application/json

🔧 Troubleshooting

Common Issues & Solutions

🚫 Container Registry Deprecated

# ❌ Old (deprecated)
gcr.io/project-id/image

# ✅ New (use Artifact Registry)
europe-west1-docker.pkg.dev/project-id/repo/image

🔐 OAuth2 Configuration Errors

# Add to application.properties
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration

🚨 403 Forbidden on Cloud Run

# Check service permissions
gcloud run services get-iam-policy message-app --region=europe-west1

# Allow unauthenticated access (if needed)
gcloud run services add-iam-policy-binding message-app \
  --region=europe-west1 \
  --member="allUsers" \
  --role="roles/run.invoker"

🔥 Firestore Connection Issues

# Disable Firestore for testing
spring.cloud.gcp.firestore.enabled=false

Viewing Logs

# View recent logs
gcloud logs read --service=message-app --region=europe-west1 --limit=50

# Stream real-time logs
gcloud logs tail --service=message-app --region=europe-west1

# Filter by severity
gcloud logs read --service=message-app --region=europe-west1 --filter="severity>=ERROR"

📊 Monitoring & Observability

  • Health Checks: /health endpoint for monitoring
  • Cloud Logging: Centralized logging in Google Cloud
  • Cloud Monitoring: Automatic metrics collection
  • Error Reporting: Automatic error tracking

🤝 Contributing

  1. 🍴 Fork the repository
  2. 🌿 Create a feature branch (git checkout -b feature/amazing-feature)
  3. 💾 Commit your changes (git commit -m 'Add amazing feature')
  4. 📤 Push to the branch (git push origin feature/amazing-feature)
  5. 🎯 Open a Pull Request

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🆘 Support

Need help? Here's how to get support:

  1. 📖 Check the troubleshooting section
  2. 📋 Review the setup guides in the repository
  3. 🐛 Create an issue for bugs or feature requests
  4. 💬 Start a discussion for questions

🙏 Acknowledgments

  • Spring Boot Team for the amazing framework
  • Google Cloud for the robust infrastructure
  • Firebase Team for Firestore

⚠️ Note: This application is designed for educational and demonstration purposes. For production use, implement additional security measures, monitoring, and error handling as needed.

🔗 Live Demo: Your Cloud Run URL

📧 Contact: Your Email

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors