Modern SwiftUI Authentication Interface
Native iOS interface built with SwiftUI & MVVM architecture
The iOS client application is a modern, native interface built using SwiftUI and follows the MVVM (Model-View-ViewModel) architecture pattern. It provides seamless integration with the AuthAPI backend, offering users a smooth and intuitive authentication experience.
| 🎨 Modern Design | ⚡ Performance | 🔒 Security | 🛠️ Development |
|---|---|---|---|
| SwiftUI gradients & animations | Async/await networking | JWT token management | MVVM architecture |
| Responsive layouts | Real-time validation | Secure storage | Clean code structure |
| iOS design guidelines | Progressive loading | Input sanitization | Modular components |
| Sign In Screen | Sign Up Screen | Email Verification Screen |
|---|---|---|
|
|
|
| Email Verification Screen | Forgot Password Screen | Reset Password Screen |
|
|
|
| Feature | Description | Status |
|---|---|---|
| 🔐 User Authentication | Login with email and password | ✅ Implemented |
| 👤 User Registration | Sign up with email verification | ✅ Implemented |
| 📧 Email Verification | Email verification status checking | ✅ Implemented |
| 🔑 Password Reset | Forgot password functionality | ✅ Implemented |
| 🎨 Modern UI | SwiftUI with gradient backgrounds | ✅ Implemented |
| ⚡ Async Operations | Modern async/await networking | ✅ Implemented |
| 🛡️ Input Validation | Real-time form validation | ✅ Implemented |
| 🔄 Loading States | Progressive loading indicators | ✅ Implemented |
- Xcode 15.0+ - Download from App Store
- iOS 16.0+ - Target deployment
- macOS Monterey 12.0+ - Development environment
# 1. Clone the repository
git clone https://github.com/ertekinbatuhan/mobile-auth-kit
cd FullStack/IOS
# 2. Open Xcode project
open LoginUI.xcodeproj
# 3. Build and run on simulator or deviceAPI Endpoint Configuration:
Edit AuthEndpoint.swift to point to your API server:
struct APIConstants {
// Production (Azure)
static let baseURL = "https://login-auth-api-azgnaec5ahavgths.westeurope-01.azurewebsites.net/api"
// Local development
// static let baseURL = "https://localhost:7045/api"
}- Email and password input fields
- Real-time validation
- Loading states during authentication
- Navigation to forgot password
- User registration form
- Password strength validation
- Email format validation
- Navigation to email verification
- Email verification status checking
- Resend verification email
- Real-time status updates
- Password reset request
- Email validation
- Success/error feedback
- Protected content display
- User authentication status
- Welcome message
IOS/LoginUI/
├── LoginUIApp.swift # Main app entry point
├── View/ # SwiftUI Views
│ ├── SignIn/ # Login screens
│ ├── SignUp/ # Registration screens
│ └── Home/ # Protected content
├── Models/ # Data models
├── Network/ # API communication
├── Core/Service/ # Authentication service
├── Components/ # Reusable UI components
└── LoginUITests/ # Unit tests
└── LoginUITests.swift # Test implementations
The iOS application includes comprehensive unit tests to ensure code quality and reliability. The test suite covers both AuthService layer and ViewModel layer testing with mock implementations.
| Component | Test Cases | Coverage |
|---|---|---|
| AuthService | 6 test cases | Authentication API calls |
| SignInViewModel | 4 test cases | Login flow validation |
| SignUpViewModel | 5 test cases | Registration flow validation |
| Mock Infrastructure | Full mocking | Network layer abstraction |
Mock Components:
MockNetworkManager- Network layer mockingAuthErrorextension - Error comparison support- Async/await testing - Modern Swift concurrency testing
| Test Case | Description | Validation |
|---|---|---|
testAuthServiceLoginSuccess |
Successful user login | Token validation |
testAuthServiceLoginFailure |
Failed login attempt | Error handling |
testAuthServiceRegisterSuccess |
Successful registration | Response validation |
testAuthServiceForgotPasswordSuccess |
Password reset request | Message validation |
testAuthServiceResetPasswordSuccess |
Password reset completion | Success confirmation |
testAuthServiceCheckEmailStatusSuccess |
Email status checking | Status validation |
SignInViewModel Tests:
- ✅ Successful login flow
- ✅ Failed login with invalid credentials
- ✅ Empty email validation
- ✅ Empty password validation
SignUpViewModel Tests:
- ✅ Successful registration flow
- ✅ Password mismatch validation
- ✅ Invalid email format validation
- ✅ Weak password validation
- ✅ Empty email validation
Xcode:
# Run all tests
Cmd + U
# Run specific test class
Cmd + Control + Option + UCommand Line:
# Navigate to iOS project
cd IOS
# Run all tests
xcodebuild test -scheme LoginUI -destination 'platform=iOS Simulator,name=iPhone 15,OS=latest'
# Run tests with coverage
xcodebuild test -scheme LoginUI -destination 'platform=iOS Simulator,name=iPhone 15,OS=latest' -enableCodeCoverage YESThe test suite follows AAA (Arrange-Act-Assert) pattern:
- Arrange: Set up mock data and dependencies
- Act: Execute the function under test
- Assert: Verify expected outcomes
Key Testing Principles:
- ✅ Isolation: Each test is independent
- ✅ Mocking: External dependencies are mocked
- ✅ Async Testing: Proper async/await testing
- ✅ Error Scenarios: Both success and failure paths tested
- ✅ Validation Logic: Form validation thoroughly tested
The iOS app communicates with the .NET backend through REST API calls:
Supported Endpoints:
POST /auth/login- User authenticationPOST /auth/register- User registrationPOST /auth/check-email-status- Email verification statusPOST /auth/forgot-password- Password reset requestPOST /auth/reset-password- Password reset completion
Modern Email-Based JWT Authentication & Authorization API
Secure, scalable and modern email-based authentication service
Setup • API Documentation • Frontend Integration • Deployment
AuthAPI is an enterprise-ready email-based authentication and authorization service built with .NET 8 and Entity Framework Core. It provides a complete security solution for modern web applications with JWT (JSON Web Token) based security infrastructure.
| Feature | Description |
|---|---|
| 📧 Email Authentication | Email-based user registration and login |
| ✅ Email Verification | Mandatory email verification system |
| 🔑 Password Reset | Secure password reset system |
| 🔐 JWT Authentication | Industry-standard JSON Web Token implementation |
| 🛡️ Secure Password Hashing | Secure password hashing with HMACSHA512 |
| 📨 HTML Email Templates | Professional-looking email templates |
| 🌐 CORS Support | Cross-origin resource sharing support |
| 🗄️ Entity Framework Core | Modern ORM for database management |
| ☁️ Azure Ready | Optimized for Azure Web App |
| 🐳 Docker Support | Container-ready deployment |
| 📦 Environment-based Config | Separate configuration for production and development environments |
- .NET 8 SDK - Download
- Visual Studio 2022 or VS Code
- Git - Download
- Gmail account - For sending emails
- Enable 2-Step Verification in your Gmail account
- Create App Password:
- Google Account → Security → 2-Step Verification → App passwords
- Select "Mail" and give a device name
- Save the generated 16-character password
# Clone the repository
git clone https://github.com/ertekinbatuhan/mobile-auth-kit
cd AuthAPI
# Restore dependencies
dotnet restore
# Copy configuration template
copy appsettings.Example.json appsettings.json
# Edit appsettings.json with your configuration:
# - Update FromEmail and SmtpUsername with your Gmail
# - Generate a strong JWT secret (minimum 32 characters)
# Set Environment Variables (Recommended for security)
set JWT_SECRET=your-super-secret-256-bit-key-minimum-32-characters
set EmailSettings__SmtpPassword=your-16-char-gmail-app-password
# Install Entity Framework tools (if not already installed)
dotnet tool install --global dotnet-ef
# Create database
dotnet ef database update
# Run the application
dotnet runBefore running the application, you MUST:
-
Copy configuration file:
copy appsettings.Example.json appsettings.json
-
Update email addresses in appsettings.json:
{ "EmailSettings": { "FromEmail": "your-gmail@gmail.com", "SmtpUsername": "your-gmail@gmail.com" } } -
Set required environment variables:
# Windows set JWT_SECRET=your-super-secret-256-bit-key-minimum-32-characters set EmailSettings__SmtpPassword=your-16-char-gmail-app-password # Linux/Mac export JWT_SECRET=your-super-secret-256-bit-key-minimum-32-characters export EmailSettings__SmtpPassword=your-16-char-gmail-app-password
🔐 IMPORTANT: JWT Secret Compatibility
If you're working with a team or want token compatibility with the production API, use the shared JWT secret:
# Shared JWT Secret (for compatibility with production)
set JWT_SECRET=AuthAPI-Production-Secret-Key-2024-v1-256bit-compatible
# Or generate your own for isolated development:
set JWT_SECRET=your-unique-development-secret-minimum-32-charactersWithout these steps, the application will NOT start!
| File | Purpose | Git Tracked |
|---|---|---|
appsettings.Example.json |
Template for configuration | ✅ Yes |
appsettings.json |
Your actual configuration | ❌ No (in .gitignore) |
Important: Never commit appsettings.json to Git as it contains sensitive information.
The API is designed to work with any frontend framework:
- Base URL:
https://localhost:7045(development) or your Azure URL (production) - Authentication: JWT Bearer tokens
- Content-Type:
application/json - CORS: Pre-configured for common development ports
| Method | Endpoint | Description |
|---|---|---|
GET |
/health |
System health check |
GET |
/ping |
Keep-alive ping (for free Azure tier) |
POST /api/auth/register - User Registration
Request:
{
"email": "user@example.com",
"password": "SecurePass123!"
}Password Requirements:
- 8-50 characters
- At least one uppercase letter
- At least one lowercase letter
- At least one number
- At least one special character (@$!%*?&)
Response (201 Created):
{
"message": "User registered successfully. Please check your email to verify your account."
}Error (400 Bad Request):
{
"message": "Validation failed.",
"errors": [
{
"Field": "Email",
"Errors": ["Please enter a valid email address."]
}
]
}POST /api/auth/login - User Login
Request:
{
"email": "user@example.com",
"password": "SecurePass123!"
}Response (200 OK):
{
"token": "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9..."
}Error (400 Bad Request - Unverified Email):
{
"message": "Please verify your email address before logging in."
}GET /api/auth/protected - Protected Endpoint Example
Request Headers:
Authorization: Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9...
Content-Type: application/json
Response (200 OK):
{
"message": "Welcome user@example.com! This is protected data and you are authorized to view it.",
"timestamp": "2024-01-24T12:00:00Z"
}Error (401 Unauthorized):
{
"message": "Unauthorized"
}┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Controllers │ ──▶│ Services │ ──▶│ Data Layer │
│ │ │ │ │ │
│ • AuthController│ │ • IAuthService │ │ • DataContext │
│ │ │ • AuthService │ │ • Entities │
│ │ │ • IEmailService │ │ │
│ │ │ • EmailService │ │ │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│ │ │
▼ ▼ ▼
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ DTOs │ │ JWT Handler │ │ SQLite |
│ │ │ │ │ │
│ • UserForLogin │ │ • Token Create │ │ • Users Table |
│ • UserForRegister│ │ • Token Verify │ │ • Email Index |
│ • EmailDto │ │ • Email Service │ │ • Migrations |
└─────────────────┘ └─────────────────┘ └─────────────────┘
- ✅ Email Verification required before login
- ✅ JWT Secret stored in environment variables
- ✅ Password Hashing with HMACSHA512
- ✅ Token Expiration for verification and reset tokens
- ✅ HTTPS enforced (provided by Azure)
- ✅ CORS configurable
- ✅ Input Validation with DTOs
- ✅ Email Enumeration Protection in forgot password
- ✅ Environment-based configuration
| Topic | Description | Status |
|---|---|---|
| Email Verification | Email verification required | ✅ Implemented |
| JWT Secret | Should be stored as environment variable | ✅ Implemented |
| Email Validation | Valid email format validation | ✅ Implemented |
| Password Policy | 8-50 chars, upper/lower case, number, special char | ✅ Implemented |
| Token Expiration | 72 hours verification, 1 hour reset | ✅ Implemented |
| Input Validation | DTO validation with data annotations | ✅ Implemented |
| URL Encoding | Automatic URL encoding in email links | ✅ Implemented |
| Rate Limiting | Protection against brute force attacks | 📋 Planned |
Azure Portal → Web App → Configuration → Application Settings:
JWT_SECRET=your-super-secure-256-bit-key-here
EmailSettings__SmtpHost=smtp.gmail.com
EmailSettings__SmtpPort=587
EmailSettings__FromName=AuthAPI
EmailSettings__FromEmail=your-gmail@gmail.com
EmailSettings__SmtpUsername=your-gmail@gmail.com
EmailSettings__SmtpPassword=your-16-char-app-password
AppSettings__BaseUrl=https://your-app-name.azurewebsites.net# Build Docker image
docker build -t authapi .
# Run container
docker run -p 8080:8080 \
-e JWT_SECRET="your-super-secret-key" \
-e EmailSettings__FromEmail="your-gmail@gmail.com" \
-e EmailSettings__SmtpUsername="your-gmail@gmail.com" \
-e EmailSettings__SmtpPassword="your-app-password" \
authapiEmail links are now automatically URL encoded and can be clicked directly!
Previous problem: + characters were converted to spaces
New solution: Links are encoded with Uri.EscapeDataString()
Example email link:
https://your-app.azurewebsites.net/api/auth/verify-email?token=LrTNAiYw4PvYtMsWzgHfbCszRKb5Ze8STdHqNWCZzKXwQ3FsJBfZ%2B96edyiWcjhd%2FG1E04yK3nEtTXcKk0K%2B8Q%3D%3D
This link works directly in browser ✅
Password reset emails contain both encoded links and raw token information for developers.
# 1. User Registration
curl -X POST https://localhost:7045/api/auth/register \
-H "Content-Type: application/json" \
-d '{"email": "test@example.com", "password": "SecurePass123!"}'
# 2. Email Verification (with token from email)
curl -X GET "https://localhost:7045/api/auth/verify-email?token=TOKEN_HERE"
# 3. User Login
curl -X POST https://localhost:7045/api/auth/login \
-H "Content-Type: application/json" \
-d '{"email": "test@example.com", "password": "SecurePass123!"}'
# 4. Protected endpoint access
curl -X GET https://localhost:7045/api/auth/protected \
-H "Authorization: Bearer YOUR_JWT_TOKEN_HERE"
# 5. Health check
curl -X GET https://localhost:7045/health- Fork this repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Email Sending Error
Error: Failed to send email
Solution:
- Check that your Gmail App Password is correct
- Verify that 2-Step Verification is active
- Ensure environment variables are set correctly
- Check that your Gmail account allows less secure apps (if using regular password)
Invalid Email Verification Token
Error: Invalid or expired verification token
Solution:
- Token must be used within 72 hours
- Request a new verification email
- Make sure you copied the entire URL token correctly
- Check if the email was already verified
JWT Configuration Error
Error: JWT secret key is not configured
Solution:
- Set the
JWT_SECRETenvironment variable - Or add a strong secret to
appsettings.json(not recommended for production) - Ensure the secret is at least 32 characters long
Database Migration Error
Error: Database migration fails
Solution:
- Delete the
auth.dbfile if it exists - Run
dotnet ef database updatemanually - Check that Entity Framework tools are installed:
dotnet tool install --global dotnet-ef
This project is licensed under the MIT License - see the LICENSE file for details.
⭐ If you find this project useful, don't forget to give it a star!
Made with ❤️ and ☕





