Overview
Discover the future of online security with our Graphical Password Authentication project using the MERN stack. This innovative project replaces traditional text-based passwords with intuitive image-based authentication, enhancing security and user experience. Perfect for students looking to learn full-stack development, this project covers MongoDB, Express.js, React, and Node.js, providing hands-on experience with modern web technologies.
Transform password security with visual authentication—making login both more secure and user-friendly through image-based recognition.
What is Graphical Password Authentication?
Graphical password authentication is an alternative authentication method where users select images or patterns instead of typing alphanumeric passwords. This approach offers several advantages:
Why Graphical Passwords?
Traditional Text Password Problems:
- Weak Passwords: Users choose simple, easy-to-guess passwords
- Forgotten Passwords: Complex passwords are hard to remember
- Shoulder Surfing: Passwords can be observed while typing
- Keylogging: Vulnerable to keylogger attacks
- Brute Force: Susceptible to automated attacks
- Password Reuse: Users reuse passwords across platforms
Graphical Password Advantages:
- Better Memory: Humans remember images better than text
- Increased Security: Larger password space with image combinations
- Shoulder Surfing Resistance: Harder to observe and replicate
- Keylogger Immunity: No keyboard input to capture
- User-Friendly: More intuitive and enjoyable authentication
- Cultural Neutrality: Works across languages and cultures
Types of Graphical Passwords
This project implements multiple graphical authentication schemes:
1. Recognition-Based (PassPoints)
- Users select specific points on an image
- Click sequence creates the password
- Multiple images for enhanced security
- Example: Click on person's eye, tree top, door handle
2. Recall-Based (Draw-a-Secret)
- Users draw a pattern on a grid
- Similar to Android pattern lock
- Custom shapes and paths
- Example: Draw a specific shape or symbol
3. Cued Recall (Image Selection)
- Users select images from a grid
- Multiple rounds with different image sets
- Recognition of pre-chosen images
- Example: Select 3 images from 9 options, repeated 3 times
Key Features
User Registration & Authentication
Registration Process
- Profile Creation: Basic user information
- Image Selection: Choose authentication images
- Password Setup:
- Select images from categories
- Choose click points on images
- Draw patterns on grids
- Set sequence order
- Confirmation: Verify graphical password
- Fallback Setup: Optional security questions
Login Process
- User Identification: Enter username/email
- Graphical Challenge: Present authentication interface
- Validation: Verify image selection/click points/pattern
- Multi-Factor: Optional additional verification
- Session Creation: Generate secure session token
Security Features
Anti-Attack Mechanisms
- Decoy Images: Add fake images to confuse attackers
- Randomization: Randomize image positions each login
- Timing Analysis: Detect automated attempts
- Attempt Limiting: Lock after failed attempts
- Session Timeout: Auto-logout for security
- HTTPS Enforcement: Encrypted communication
- CAPTCHA Integration: Prevent bot attacks
Password Storage
- Hashing: Hash image coordinates/patterns
- Salting: Unique salt for each user
- Encryption: Encrypt sensitive data
- No Plain Storage: Never store raw passwords
User Experience
Intuitive Interface
- Visual Feedback: Clear selection indicators
- Progress Tracking: Show authentication steps
- Error Handling: Helpful error messages
- Responsive Design: Works on all devices
- Accessibility: Support for screen readers
- Customization: Personalize image categories
Account Management
- Password Reset: Image-based recovery
- Profile Update: Change authentication images
- Security Settings: Adjust security level
- Login History: View recent logins
- Device Management: Manage trusted devices
Tech Stack
Frontend (React)
- React 18+: Modern UI library
- React Router: Navigation and routing
- Redux Toolkit: Global state management
- Material-UI: Component library
- Canvas API: Drawing interface for patterns
- Axios: HTTP requests
- React Hook Form: Form management
- Framer Motion: Smooth animations
- React-Toastify: Notifications
Backend (Node.js & Express)
- Node.js 16+: JavaScript runtime
- Express.js: Web framework
- MongoDB & Mongoose: Database and ODM
- JWT: Token-based authentication
- Bcrypt: Password hashing
- Crypto: Encryption utilities
- Multer: Image upload handling
- Sharp: Image processing
- Express Validator: Input validation
- Helmet: Security headers
- Rate Limiter: Brute force protection
- CORS: Cross-origin requests
Database (MongoDB)
- User Collection: User profiles
- Image Collection: Authentication images
- Session Collection: Active sessions
- Audit Collection: Login attempts
Additional Tools
- Cloudinary/AWS S3: Image storage
- Redis: Session management
- Winston: Logging
- Jest: Testing framework
- Supertest: API testing
Project Structure
graphical-password-auth/
├─ client/ # React frontend
│ ├─ public/
│ │ ├─ images/
│ │ │ ├─ categories/ # Image categories
│ │ │ │ ├─ animals/
│ │ │ │ ├─ nature/
│ │ │ │ ├─ objects/
│ │ │ │ ├─ people/
│ │ │ │ └─ places/
│ │ │ └─ grid-patterns/
│ │ └─ index.html
│ ├─ src/
│ │ ├─ components/
│ │ │ ├─ auth/
│ │ │ │ ├─ Login.jsx
│ │ │ │ ├─ Register.jsx
│ │ │ │ ├─ ImageSelector.jsx
│ │ │ │ ├─ ClickPointAuth.jsx
│ │ │ │ ├─ PatternDrawer.jsx
│ │ │ │ └─ PasswordReset.jsx
│ │ │ ├─ dashboard/
│ │ │ │ ├─ UserDashboard.jsx
│ │ │ │ ├─ SecuritySettings.jsx
│ │ │ │ ├─ LoginHistory.jsx
│ │ │ │ └─ ProfileSettings.jsx
│ │ │ └─ common/
│ │ │ ├─ Navbar.jsx
│ │ │ ├─ PrivateRoute.jsx
│ │ │ ├─ LoadingSpinner.jsx
│ │ │ └─ ErrorBoundary.jsx
│ │ ├─ pages/
│ │ │ ├─ Home.jsx
│ │ │ ├─ LoginPage.jsx
│ │ │ ├─ RegisterPage.jsx
│ │ │ ├─ Dashboard.jsx
│ │ │ └─ NotFound.jsx
│ │ ├─ redux/
│ │ │ ├─ store.js
│ │ │ ├─ slices/
│ │ │ │ ├─ authSlice.js
│ │ │ │ ├─ userSlice.js
│ │ │ │ └─ uiSlice.js
│ │ │ └─ api/
│ │ │ └─ authApi.js
│ │ ├─ utils/
│ │ │ ├─ validators.js
│ │ │ ├─ imageHelpers.js
│ │ │ ├─ patternHelpers.js
│ │ │ └─ constants.js
│ │ ├─ hooks/
│ │ │ ├─ useAuth.js
│ │ │ ├─ useCanvas.js
│ │ │ └─ useClickPoints.js
│ │ ├─ styles/
│ │ ├─ App.jsx
│ │ └─ index.js
│ └─ package.json
├─ server/ # Node.js backend
│ ├─ config/
│ │ ├─ database.js # MongoDB connection
│ │ ├─ cloudinary.js # Image storage
│ │ └─ redis.js # Session store
│ ├─ models/
│ │ ├─ User.js # User schema
│ │ ├─ GraphicalPassword.js # Password schema
│ │ ├─ Session.js # Session schema
│ │ ├─ LoginAttempt.js # Audit schema
│ │ └─ Image.js # Image metadata
│ ├─ controllers/
│ │ ├─ authController.js # Authentication logic
│ │ ├─ userController.js # User management
│ │ ├─ imageController.js # Image operations
│ │ └─ securityController.js # Security features
│ ├─ routes/
│ │ ├─ auth.js # Auth routes
│ │ ├─ user.js # User routes
│ │ ├─ images.js # Image routes
│ │ └─ security.js # Security routes
│ ├─ middleware/
│ │ ├─ auth.js # JWT verification
│ │ ├─ validation.js # Input validation
│ │ ├─ rateLimiter.js # Rate limiting
│ │ ├─ errorHandler.js # Error handling
│ │ └─ logger.js # Request logging
│ ├─ services/
│ │ ├─ passwordService.js # Password hashing/verification
│ │ ├─ imageService.js # Image processing
│ │ ├─ sessionService.js # Session management
│ │ └─ emailService.js # Email notifications
│ ├─ utils/
│ │ ├─ crypto.js # Encryption utilities
│ │ ├─ validators.js # Validation helpers
│ │ └─ helpers.js # General helpers
│ ├─ tests/
│ │ ├─ auth.test.js
│ │ ├─ password.test.js
│ │ └─ security.test.js
│ ├─ server.js # Entry point
│ └─ package.json
├─ .env.example
├─ .gitignore
└─ README.md
Database Schema
User Model
const userSchema = new mongoose.Schema({
username: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
fullName: { type: String, required: true },
authMethod: {
type: String,
enum: ['image-selection', 'click-points', 'pattern-draw'],
required: true
},
isActive: { type: Boolean, default: true },
isLocked: { type: Boolean, default: false },
lockUntil: Date,
failedLoginAttempts: { type: Number, default: 0 },
lastLogin: Date,
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now }
});
GraphicalPassword Model
const graphicalPasswordSchema = new mongoose.Schema({
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
authMethod: { type: String, required: true },
// For image selection method
selectedImages: [{
round: Number,
imageIds: [String],
category: String
}],
// For click points method
clickPoints: [{
imageId: String,
coordinates: [{
x: Number,
y: Number,
tolerance: { type: Number, default: 20 }
}]
}],
// For pattern draw method
pattern: {
gridSize: { type: Number, default: 3 },
hashedPattern: String,
salt: String
},
salt: { type: String, required: true },
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now }
});
LoginAttempt Model
const loginAttemptSchema = new mongoose.Schema({
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
username: String,
ipAddress: String,
userAgent: String,
success: { type: Boolean, required: true },
attemptMethod: String,
failureReason: String,
timestamp: { type: Date, default: Date.now }
});
Setup & Installation
Prerequisites
- Node.js 16+ and npm
- MongoDB (local or MongoDB Atlas)
- Redis (optional, for session storage)
- Cloudinary account (for image storage)
Installation Steps
1. Clone Repository
git clone <repository-url>
cd graphical-password-auth
2. Install Server Dependencies
cd server
npm install
3. Install Client Dependencies
cd ../client
npm install
cd ..
4. Configure Environment Variables
Create server/.env
:
# Server
PORT=5000
NODE_ENV=development
# Database
MONGO_URI=mongodb://localhost:27017/graphical-auth
# Or MongoDB Atlas:
# MONGO_URI=mongodb+srv://username:password@cluster.mongodb.net/graphical-auth
# JWT
JWT_SECRET=your-super-secret-jwt-key
JWT_EXPIRE=24h
# Encryption
ENCRYPTION_KEY=your-32-character-encryption-key
ENCRYPTION_IV=your-16-character-iv
# Cloudinary
CLOUDINARY_CLOUD_NAME=your-cloud-name
CLOUDINARY_API_KEY=your-api-key
CLOUDINARY_API_SECRET=your-api-secret
# Redis (optional)
REDIS_URL=redis://localhost:6379
# Email (for notifications)
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_USER=your-email@gmail.com
EMAIL_PASSWORD=your-app-password
# Security
MAX_LOGIN_ATTEMPTS=5
LOCK_DURATION_MINUTES=30
SESSION_TIMEOUT_HOURS=24
# Frontend URL
CLIENT_URL=http://localhost:3000
Create client/.env
:
REACT_APP_API_URL=http://localhost:5000/api
REACT_APP_MAX_IMAGE_SIZE=5242880
REACT_APP_GRID_SIZE=3
5. Seed Image Database (Optional)
cd server
npm run seed:images
6. Start Development Servers
# Terminal 1: Start backend
cd server
npm run dev
# Terminal 2: Start frontend
cd client
npm start
Application available at:
- Frontend: http://localhost:3000
- Backend API: http://localhost:5000
Implementation Details
1. Image Selection Authentication
Registration:
// User selects 3-5 images from each category over 3 rounds
const setupImageAuth = async (userId, selections) => {
const rounds = [
{ round: 1, imageIds: selections.round1, category: 'animals' },
{ round: 2, imageIds: selections.round2, category: 'places' },
{ round: 3, imageIds: selections.round3, category: 'objects' }
];
const salt = await bcrypt.genSalt(10);
const hashedSelections = await hashImageSelections(rounds, salt);
await GraphicalPassword.create({
user: userId,
authMethod: 'image-selection',
selectedImages: hashedSelections,
salt
});
};
Login:
// Verify user selections match stored password
const verifyImageAuth = async (userId, loginSelections) => {
const password = await GraphicalPassword.findOne({ user: userId });
for (let round of password.selectedImages) {
const userSelection = loginSelections[`round${round.round}`];
const isMatch = await verifyImageSelection(
userSelection,
round.imageIds,
password.salt
);
if (!isMatch) return false;
}
return true;
};
2. Click Points Authentication
Registration:
// User clicks specific points on images
const setupClickPointAuth = async (userId, clickData) => {
const clickPoints = clickData.map(click => ({
imageId: click.imageId,
coordinates: click.points.map(point => ({
x: point.x,
y: point.y,
tolerance: 20 // pixels
}))
}));
const salt = await bcrypt.genSalt(10);
const hashedPoints = await hashClickPoints(clickPoints, salt);
await GraphicalPassword.create({
user: userId,
authMethod: 'click-points',
clickPoints: hashedPoints,
salt
});
};
Verification:
// Verify clicks are within tolerance of stored points
const verifyClickPoints = (loginPoint, storedPoint, tolerance) => {
const distance = Math.sqrt(
Math.pow(loginPoint.x - storedPoint.x, 2) +
Math.pow(loginPoint.y - storedPoint.y, 2)
);
return distance <= tolerance;
};
3. Pattern Draw Authentication
Registration:
// User draws pattern on grid
const setupPatternAuth = async (userId, pattern) => {
const salt = await bcrypt.genSalt(10);
const patternString = pattern.join('-'); // e.g., "0-1-2-5-4"
const hashedPattern = await bcrypt.hash(patternString, salt);
await GraphicalPassword.create({
user: userId,
authMethod: 'pattern-draw',
pattern: {
gridSize: 3,
hashedPattern,
salt
},
salt
});
};
Canvas Implementation:
// React component for pattern drawing
const PatternDrawer = () => {
const canvasRef = useRef(null);
const [pattern, setPattern] = useState([]);
const handleTouch = (e) => {
const canvas = canvasRef.current;
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
// Determine grid cell
const cellSize = canvas.width / 3;
const col = Math.floor(x / cellSize);
const row = Math.floor(y / cellSize);
const cellIndex = row * 3 + col;
// Add to pattern if not already included
if (!pattern.includes(cellIndex)) {
setPattern([...pattern, cellIndex]);
drawLine(/* draw visual feedback */);
}
};
return <canvas ref={canvasRef} onMouseDown={handleTouch} />;
};
Security Implementation
Rate Limiting
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 5, // 5 attempts
message: 'Too many login attempts, please try again later',
standardHeaders: true,
legacyHeaders: false
});
router.post('/login', loginLimiter, authController.login);
Account Locking
const handleFailedLogin = async (userId) => {
const user = await User.findById(userId);
user.failedLoginAttempts += 1;
if (user.failedLoginAttempts >= MAX_LOGIN_ATTEMPTS) {
user.isLocked = true;
user.lockUntil = new Date(Date.now() + LOCK_DURATION_MS);
}
await user.save();
};
Session Management
const createSession = async (userId) => {
const token = jwt.sign(
{ userId, timestamp: Date.now() },
JWT_SECRET,
{ expiresIn: JWT_EXPIRE }
);
await Session.create({
user: userId,
token,
expiresAt: new Date(Date.now() + SESSION_TIMEOUT_MS)
});
return token;
};
API Endpoints
Authentication
POST /api/auth/register # Register new user
POST /api/auth/setup-password # Setup graphical password
POST /api/auth/login # Login with graphical password
POST /api/auth/logout # Logout
POST /api/auth/refresh # Refresh JWT token
POST /api/auth/reset-password # Reset password
User Management
GET /api/user/profile # Get user profile
PUT /api/user/profile # Update profile
PUT /api/user/change-password # Change graphical password
GET /api/user/login-history # Get login history
GET /api/user/sessions # Get active sessions
DELETE /api/user/session/:id # Revoke session
Images
GET /api/images/categories # Get image categories
GET /api/images/:category # Get images by category
GET /api/images/random # Get random images for login
Security
POST /api/security/unlock # Request account unlock
GET /api/security/check-status # Check account status
POST /api/security/report-suspicious # Report suspicious activity
User Workflows
Registration Workflow
-
Basic Information
- Enter username, email, full name
- Choose authentication method
- Click "Next"
-
Password Setup
- Image Selection: Select images across 3 rounds
- Click Points: Click specific points on images
- Pattern Draw: Draw pattern on grid
- Set security questions (optional)
-
Confirmation
- Repeat authentication to confirm
- Review and submit
- Account created
Login Workflow
-
User Identification
- Enter username or email
- System identifies auth method
-
Graphical Authentication
- Image Selection: Select correct images from randomized grid
- Click Points: Click correct points on images
- Pattern Draw: Redraw the pattern
-
Verification
- System verifies authentication
- Create session on success
- Redirect to dashboard
-
Failed Attempt Handling
- Show error message
- Increment attempt counter
- Lock account after max attempts
Security Benefits
Resistance to Common Attacks
Dictionary Attacks
- Not applicable—no text to brute force
- Image combinations create vast password space
Phishing
- Harder to replicate graphical interface
- Users trained to recognize authentic UI
Keylogging
- No keyboard input to capture
- Mouse movements harder to interpret
Shoulder Surfing
- Click points not easily observable
- Randomized image positions
Social Engineering
- Difficult to describe graphical passwords
- Can't easily share selections
Password Space Calculation
Image Selection Method:
- 3 rounds × 9 images per round
- Select 3 from 9 = C(9,3) = 84 combinations
- Total: 84³ = 592,704 combinations
Click Points Method:
- 5 points on 800×600 image
- 20-pixel tolerance = ~2,400 possible points
- Total: 2,400⁵ = 7.96 × 10¹⁶ combinations
Pattern Draw:
- 3×3 grid = 9 points
- Minimum 4 points pattern
- P(9,4) = 3,024 combinations (conservative)
Learning Outcomes
Frontend Development
- React Fundamentals: Components, hooks, state management
- Canvas API: Drawing and pattern recognition
- Event Handling: Mouse/touch events for interactions
- Responsive Design: Mobile-friendly authentication
- State Management: Redux for complex auth flows
- Form Handling: Multi-step registration
Backend Development
- Express.js: RESTful API design
- MongoDB: Schema design for auth data
- Authentication: JWT token management
- Security: Hashing, salting, encryption
- Rate Limiting: Protect against brute force
- Session Management: Secure session handling
Security Concepts
- Authentication Systems: Alternative auth methods
- Password Security: Hashing and salting
- Attack Prevention: Brute force, phishing protection
- Cryptography: Encryption and decryption
- Security Best Practices: OWASP guidelines
- Threat Modeling: Identify vulnerabilities
Full-Stack Skills
- MERN Architecture: Complete stack integration
- API Design: Client-server communication
- Error Handling: Graceful failure management
- Testing: Unit and integration tests
- Deployment: Production configuration
Advanced Features
Multi-Factor Authentication
- Combine graphical with text password
- SMS/Email verification
- Biometric integration (fingerprint, face)
- Hardware token support
Accessibility
- Audio cues for visually impaired
- Keyboard navigation support
- High contrast mode
- Screen reader compatibility
Analytics Dashboard
- Login success/failure rates
- Popular attack patterns
- User behavior analysis
- Security incident reports
Mobile Application
- React Native mobile app
- Touch-optimized patterns
- Biometric fallback
- Offline pattern verification
Testing
Backend Tests
cd server
npm test
# Specific tests
npm test -- auth.test.js
npm test -- password.test.js
# Coverage
npm run test:coverage
Frontend Tests
cd client
npm test
# Component tests
npm test -- PatternDrawer.test.js
npm test -- ImageSelector.test.js
Security Testing
# Penetration testing
npm run test:security
# Load testing
npm run test:load
Deployment
Backend Deployment
# Build for production
cd server
NODE_ENV=production npm install
# Deploy to Heroku/Railway/Render
git push heroku main
Frontend Deployment
# Build production bundle
cd client
npm run build
# Deploy to Vercel/Netlify
vercel --prod
Database
- Use MongoDB Atlas for production
- Enable authentication
- Set up backups
- Configure indexes
Security Checklist
- Enable HTTPS/SSL
- Set secure cookie flags
- Configure CORS properly
- Enable rate limiting
- Set up monitoring
- Configure firewall
- Enable database encryption
- Set up backup strategy
Performance Optimization
Frontend
- Lazy load images
- Implement caching
- Optimize canvas rendering
- Code splitting
- Image compression
Backend
- Database indexing
- Query optimization
- Redis caching
- Response compression
- CDN for images
Challenges & Solutions
Challenge: Large Image Storage
Solution: Use CDN (Cloudinary/AWS S3), lazy loading, image optimization
Challenge: Pattern Recognition Accuracy
Solution: Implement tolerance zones, normalize coordinates, use hashing
Challenge: Mobile Responsiveness
Solution: Touch events, responsive grids, scalable canvas
Challenge: User Memory
Solution: Practice mode, hints, reset options, familiar images
Best Practices
Code Quality
- Follow ESLint rules
- Use TypeScript (optional)
- Write meaningful comments
- Modular component design
- DRY principle
Security
- Never store plain passwords
- Use HTTPS in production
- Implement CSRF protection
- Validate all inputs
- Regular security audits
User Experience
- Clear instructions
- Visual feedback
- Error recovery
- Progressive disclosure
- Consistent UI
Resources
- OWASP Authentication Cheat Sheet
- Graphical Password Research
- Canvas API Documentation
- JWT Best Practices
- MongoDB Security Checklist
Use Cases
Academic Projects
- Final Year Project: Complete authentication system
- Security Course: Demonstrate alternative auth
- HCI Research: User experience studies
- Capstone Project: Full-stack application
Real-World Applications
- Banking Apps: Secure mobile banking
- Healthcare: Patient data access
- Corporate: Internal systems
- Gaming: Account protection
- Education: Student portals
Portfolio
- Showcase security knowledge
- Demonstrate MERN skills
- Display UX design
- Highlight problem-solving
Future Enhancements
- AI-Based Authentication: Behavioral biometrics
- 3D Passwords: VR/AR authentication
- Blockchain Integration: Decentralized identity
- Voice Recognition: Multi-modal auth
- Gesture Recognition: Camera-based patterns
Conclusion
The Graphical Password Authentication System represents a modern approach to security that balances usability with protection. By leveraging the MERN stack, this project provides students with comprehensive experience in full-stack development while exploring innovative authentication methods.
This project goes beyond traditional password systems, offering insights into human-computer interaction, security psychology, and advanced web development. The visual nature of the authentication makes it more memorable for users while providing strong security through large password spaces and resistance to common attacks.
For students, this project offers invaluable learning opportunities in React frontend development, Node.js backend architecture, MongoDB database design, and security implementation. The practical applications range from mobile banking to healthcare systems, making it highly relevant for real-world scenarios.
Whether you're building a portfolio, completing an academic project, or exploring alternative authentication methods, this Graphical Password Authentication System provides a solid foundation for understanding modern security practices while mastering the MERN stack. The combination of enhanced security, improved user experience, and comprehensive full-stack implementation makes this an excellent project for advancing your web development and security skills.