Skip to content

A full-stack solution featuring a SwiftUI iOS App and a .NET 8 REST API, containerized with Docker for seamless deployment on Azure Web Apps. Implements secure JWT authentication, making it a complete, cloud-ready mobile authentication system.

License

Notifications You must be signed in to change notification settings

ifieryarrows/mobile-auth-kit

Β 
Β 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

22 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Β 

πŸ“± iOS Client Application

Modern SwiftUI Authentication Interface

SwiftUI iOS Xcode MVVM

Native iOS interface built with SwiftUI & MVVM architecture

πŸ“± Screenshots β€’ ⚑ Features β€’ πŸš€ Setup β€’ πŸ—οΈ Architecture


πŸ“‹ iOS Overview

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.

🎯 Key Highlights

🎨 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

πŸ“± Screenshots

Sign In Screen Sign Up Screen Email Verification Screen
Ekran 3 Ekran 4 Ekran 6
Email Verification Screen Forgot Password Screen Reset Password Screen
Ekran 1 Ekran 2 Ekran 5

πŸ› οΈ iOS Technology Stack

Frontend Architecture Network UI Framework
SwiftUI MVVM URLSession Async/Await

✨ iOS Features

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

πŸš€ iOS Setup & Installation

Prerequisites

  • Xcode 15.0+ - Download from App Store
  • iOS 16.0+ - Target deployment
  • macOS Monterey 12.0+ - Development environment

πŸ“¦ Installation Steps

# 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 device

βš™οΈ Configuration

API 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"
}

πŸ“± iOS Screens

πŸ” Sign In Screen

  • Email and password input fields
  • Real-time validation
  • Loading states during authentication
  • Navigation to forgot password

πŸ‘€ Sign Up Screen

  • User registration form
  • Password strength validation
  • Email format validation
  • Navigation to email verification

πŸ“§ Email Verification Screen

  • Email verification status checking
  • Resend verification email
  • Real-time status updates

πŸ”‘ Forgot Password Screen

  • Password reset request
  • Email validation
  • Success/error feedback

🏠 Home Screen

  • Protected content display
  • User authentication status
  • Welcome message

πŸ—οΈ iOS Project Structure

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

πŸ§ͺ iOS Unit Testing

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.

πŸ“Š Test Coverage

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

πŸ”§ Test Infrastructure

Mock Components:

  • MockNetworkManager - Network layer mocking
  • AuthError extension - Error comparison support
  • Async/await testing - Modern Swift concurrency testing

πŸ“ AuthService Tests

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

πŸ“± ViewModel Tests

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

πŸš€ Running Tests

Xcode:

# Run all tests
Cmd + U

# Run specific test class
Cmd + Control + Option + U

Command 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 YES

🎯 Test Philosophy

The 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

πŸ”— iOS-Backend Integration

The iOS app communicates with the .NET backend through REST API calls:

Supported Endpoints:

  • POST /auth/login - User authentication
  • POST /auth/register - User registration
  • POST /auth/check-email-status - Email verification status
  • POST /auth/forgot-password - Password reset request
  • POST /auth/reset-password - Password reset completion

πŸ” AuthAPI

Modern Email-Based JWT Authentication & Authorization API

.NET 8 Entity Framework SQLite Azure Docker MailKit

Secure, scalable and modern email-based authentication service

Setup β€’ API Documentation β€’ Frontend Integration β€’ Deployment


πŸ“‹ Overview

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.

✨ Features

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

πŸš€ Quick Setup

Prerequisites

  • .NET 8 SDK - Download
  • Visual Studio 2022 or VS Code
  • Git - Download
  • Gmail account - For sending emails

πŸ“§ Gmail SMTP Setup

  1. Enable 2-Step Verification in your Gmail account
  2. Create App Password:
    • Google Account β†’ Security β†’ 2-Step Verification β†’ App passwords
    • Select "Mail" and give a device name
    • Save the generated 16-character password

πŸ“¦ Local Setup

# 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 run

⚠️ IMPORTANT: First Time Setup

Before running the application, you MUST:

  1. Copy configuration file:

    copy appsettings.Example.json appsettings.json
  2. Update email addresses in appsettings.json:

    {
      "EmailSettings": {
        "FromEmail": "your-gmail@gmail.com",
        "SmtpUsername": "your-gmail@gmail.com"
      }
    }
  3. 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-characters

⚠️ Note: Using the same JWT_SECRET ensures token compatibility between instances. Using different secrets will create incompatible tokens.

Without these steps, the application will NOT start!

πŸ”§ Configuration Files

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.

🌐 Frontend Integration

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

πŸ”Œ API Endpoints

πŸ“Š Endpoint Overview

Method Endpoint Description Auth Status
POST /api/auth/register User registration with email ❌ Active
GET /api/auth/verify-email Email verification ❌ Active
POST /api/auth/resend-verification Resend verification email ❌ Active
POST /api/auth/login User login with email ❌ Active
POST /api/auth/forgot-password Send password reset email ❌ Active
POST /api/auth/reset-password Set new password ❌ Active
GET /api/auth/protected Protected data access βœ… Active
POST /api/auth/check-email-status Check email status ❌ Active
POST /api/auth/delete-account Request account deletion βœ… Active
GET /api/auth/confirm-account-deletion Confirm account deletion ❌ Active
DELETE /api/auth/admin/delete-account/{email} Admin account deletion βœ… Active

πŸ§ͺ Health Check Endpoints

Method Endpoint Description
GET /health System health check
GET /ping Keep-alive ping (for free Azure tier)

πŸ“ Example API Usage

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"
}

πŸ—οΈ Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   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    |
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ› οΈ Technology Stack

Backend Database Security Email DevOps
.NET SQLite JWT Gmail Docker
ASP.NET Core Entity Framework HMACSHA512 MailKit Azure

πŸ”’ Security

πŸ›‘οΈ Security Features

  • βœ… 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

⚠️ Security Notes

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

☁️ Deployment

🌐 Azure Web App

1️⃣ Set Environment Variables

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

2️⃣ Docker Support

# 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" \
  authapi

πŸ“§ Email Features

βœ… Email Verification Links

Email 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

Password reset emails contain both encoded links and raw token information for developers.


πŸ§ͺ Testing

πŸ“Š Test Scenarios

# 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

🀝 Contributing

  1. Fork this 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

πŸ†˜ Troubleshooting

Email Sending Error

Error: Failed to send email

Solution:

  1. Check that your Gmail App Password is correct
  2. Verify that 2-Step Verification is active
  3. Ensure environment variables are set correctly
  4. Check that your Gmail account allows less secure apps (if using regular password)
Invalid Email Verification Token

Error: Invalid or expired verification token

Solution:

  1. Token must be used within 72 hours
  2. Request a new verification email
  3. Make sure you copied the entire URL token correctly
  4. Check if the email was already verified
JWT Configuration Error

Error: JWT secret key is not configured

Solution:

  1. Set the JWT_SECRET environment variable
  2. Or add a strong secret to appsettings.json (not recommended for production)
  3. Ensure the secret is at least 32 characters long
Database Migration Error

Error: Database migration fails

Solution:

  1. Delete the auth.db file if it exists
  2. Run dotnet ef database update manually
  3. Check that Entity Framework tools are installed: dotnet tool install --global dotnet-ef

πŸ“„ License

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 β˜•

About

A full-stack solution featuring a SwiftUI iOS App and a .NET 8 REST API, containerized with Docker for seamless deployment on Azure Web Apps. Implements secure JWT authentication, making it a complete, cloud-ready mobile authentication system.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • C# 68.3%
  • Swift 31.2%
  • Dockerfile 0.5%