Files
CodingSandbox/winforms_security_sandbox.md
T
2026-05-31 15:08:26 +03:00

20 KiB
Raw Blame History

📄 .NET 4.8.1 WinForms Authentication & Security Sandbox Manual

Welcome to the technical documentation of the C# WinForms Authentication & Security Sandbox. This manual is organized into two complete sections: Section 1 in English and Bölüm 2 in Turkish.


SECTION 1: English (Technical Manual)

A premium, modern desktop authentication and user management sandbox designed for C# WinForms targeting .NET Framework 4.8.1.

🏗 Architecture & Design

The application utilizes a clean Separation of Concerns (SoC) model with shared service layers and event-driven updates.

graph TD
    classDef main fill:#1E293B,stroke:#0EA5E9,stroke-width:2px,color:#fff;
    classDef service fill:#0F172A,stroke:#6366F1,stroke-width:2px,color:#fff;
    classDef model fill:#1E293B,stroke:#10B981,stroke-width:2px,color:#fff;

    MainForm[MainForm<br/>Dashboard]:::main
    LoginDialog[LoginDialog<br/>Sign In]:::main
    UserSettings[UserSettings<br/>Directory Manager]:::main
    
    SessionManager[SessionManager<br/>State & Events]:::service
    User[User Model]:::model

    MainForm -->|Subscribes to Events| SessionManager
    MainForm -->|Opens dialog| LoginDialog
    MainForm -->|Opens dialog| UserSettings

    LoginDialog -->|Authenticates| SessionManager
    UserSettings -->|Modifies directories| SessionManager
    
    SessionManager -->|Manages| User

📂 Project Directory Structure

Here are the key files created for this project in UserPermissionTest_CS_WinForms:

  • 📄 UserPermissionTest_CS_WinForms.csproj: SDK-style project file configured for net481 with Windows Forms enabled and Newtonsoft.Json package installed.
  • 📄 Program.cs: Main execution entry point.
  • 📄 User.cs: Object model for users holding Username, Full Name, Password (hashed), and Permissions list.
  • 📄 SessionManager.cs: Dynamic state and session service utilizing cross-form event notifications (SessionStateChanged, UsersUpdated).
  • 📄 PasswordHasher.cs: Cryptographic utility providing one-way SHA-256 password hashing and validation.
  • 🖥 MainForm:
  • 🖥 LoginDialog:
  • 🖥 UserSettings:
    • UserSettings.cs: Directory editor, user details modifier, and dynamic system permissions register. Supports secure password placeholders and toggles.
    • UserSettings.Designer.cs: Side-by-side catalog and profile fields.

🗄️ Repository Pattern & PostgreSQL Migration Path

To address future scalability and facilitate a seamless transition to a relational database like PostgreSQL, the data layer has been decoupled using the Repository Pattern:

graph LR
    SessionManager -->|Uses| IUserRepository
    IUserRepository <|.. JsonUserRepository
    IUserRepository <|.. PostgreSqlUserRepository
    
    style IUserRepository fill:#1E293B,stroke:#F59E0B,stroke-width:2px,color:#fff
    style JsonUserRepository fill:#1E293B,stroke:#10B981,stroke-width:2px
    style PostgreSqlUserRepository fill:#1E293B,stroke:#0EA5E9,stroke-width:2px,stroke-dasharray: 5 5

Decoupled Interfaces:

  • IUserRepository.cs: Contract layer. Declares LoadUsers, SaveUsers, LoadPermissions, and SavePermissions.
  • JsonUserRepository.cs: Local file-based (JSON) storage provider using Newtonsoft.Json. Writes/reads database parameters to local files users.json / permissions.json inside output build directories.

🐘 PostgreSQL Migration Steps:

When you decide to migrate to PostgreSQL, you only need to follow these simple steps:

  1. Install Npgsql (PostgreSQL Client) and a mapper like EntityFramework or Dapper via NuGet.
  2. Implement a new class adhering to IUserRepository:
    public class PostgreSqlUserRepository : IUserRepository
    {
        private readonly string _connectionString;
        public PostgreSqlUserRepository(string connString) => _connectionString = connString;
    
        public List<User> LoadUsers() { /* DB query */ }
        public void SaveUsers(List<User> users) { /* DB save */ }
        public List<string> LoadPermissions() { /* DB query */ }
        public void SavePermissions(List<string> permissions) { /* DB save */ }
    }
    
  3. Swap a single line in SessionManager.cs:
    // Old: private static readonly IUserRepository UserRepository = new JsonUserRepository();
    // New:
    private static readonly IUserRepository UserRepository = new PostgreSqlUserRepository("Host=localhost;Database=mydb;Username=postgres;Password=pwd");
    
  4. Zero UI Code Modification: None of the Windows Forms (MainForm, LoginDialog, UserSettings) will require any edits. The application will immediately pull from and write to PostgreSQL.

🔒 Role-Based Access Control (RBAC)

The application enforces fine-grained authorization constraints on dashboard actions based on active session permissions:

  • Locked State (Not Logged In):
    • The Manage Users button is completely disabled and marked as 🔒 Manage Users.
  • Unauthorized State (Logged In without privilege):
    • If a user logs in (e.g., user) but does not have the Manage Users or Full Control permission:
      • The directory button is locked and updated to 🔒 Manage Users (Locked).
      • Client-side defensive checks verify permissions upon any attempt to click the control, displaying a security alert if breached.
  • Authorized State (Logged In with privilege):
    • If a user logs in (e.g., admin) and has the Manage Users or Full Control permission:
      • The directory button becomes fully active and updates to 👥 Manage Users.

🔐 Cryptographic Security & Password UX

The application implements enterprise-level password security and high-fidelity visibility controls:

  • SHA-256 One-Way Hashing:
    • Passwords are never stored or processed in plain text. PasswordHasher.cs computes a secure SHA-256 hash using System.Security.Cryptography for database-compatible security.
  • On-the-Fly Hashing Migration:
    • The file parser in JsonUserRepository dynamically intercepts old plain-text database profiles on startup. If a legacy plain-text password is encountered, it hashes it instantly and saves the migrated database back to disk transparently.
  • Secure Administrator Directory Workflows:
    • When loading user profiles in UserSettings, the password is never sent to the UI. Instead, a protective bullet mask ●●●●●●●● is shown.
    • If the administrator edits other details but leaves the password field containing the mask ●●●●●●●●, the system detects this and keeps the current hashed password completely intact.
    • If the administrator writes a new string, it hashes and overrides it.
  • Interactive Password Toggles (Show/Hide):
    • An elegant, borderless eye button (btnTogglePassword with 👁/🙈 states) is added adjacent to password boxes in LoginDialog and UserSettings to dynamically toggle characters between masked bullets '•' and plain text.

🎨 Visual Design Choices

  • Harmonious Palettes:
    • Header Panels: Slate Navy (#1E293B)
    • Buttons: Indigo Purple (#6366F1) and Emerald Green (#10B981)
    • Backgrounds: White (#FFFFFF) with contrasting light slate fills (#F8FAFC, #F1F5F9)
  • Typography: Clean Segoe UI fonts utilizing structured bold/semi-bold weight hierarchy for high legibility.
  • Badges & Lists: Green/Red status badge for signed-in sessions and bulleted checklists displaying privileges.

🧪 Pre-Configured Test Credentials

For quick testing, the sandbox initializes with the following default users:

  1. Administrator User

    • Username: admin
    • Password: admin
    • Permissions: View Dashboard, Edit Settings, Manage Users, Full Control
  2. Standard User

    • Username: user
    • Password: user
    • Permissions: View Dashboard


BÖLÜM 2: Türkçe (Teknik Kılavuz)

C# WinForms ortamında geliştirilen ve .NET Framework 4.8.1 sürümünü hedefleyen modern, yüksek güvenlikli kullanıcı oturum ve yetki yönetim laboratuvarı belgesidir.

🏗 Mimari Tasarım ve Akış

Uygulama, veri katmanını kullanıcı arayüzünden tamamen ayıran temiz bir Sorumlulukların Ayrılması (SoC) mimarisi ve olay güdümlü (event-driven) güncelleme akışları kullanır.

graph TD
    classDef main fill:#1E293B,stroke:#0EA5E9,stroke-width:2px,color:#fff;
    classDef service fill:#0F172A,stroke:#6366F1,stroke-width:2px,color:#fff;
    classDef model fill:#1E293B,stroke:#10B981,stroke-width:2px,color:#fff;

    MainForm[MainForm<br/>Dashboard / Panel]:::main
    LoginDialog[LoginDialog<br/>Giriş Ekranı]:::main
    UserSettings[UserSettings<br/>Dizin ve Ayarlar]:::main
    
    SessionManager[SessionManager<br/>Durum ve Olaylar]:::service
    User[User Modeli]:::model

    MainForm -->|Olaylara Abone Olur| SessionManager
    MainForm -->|Açılır Dialog| LoginDialog
    MainForm -->|Açılır Dialog| UserSettings

    LoginDialog -->|Kimlik Doğrular| SessionManager
    UserSettings -->|Dizini Düzenler| SessionManager
    
    SessionManager -->|Yönetir| User

📂 Proje Dizin Yapısı

UserPermissionTest_CS_WinForms dizininde oluşturulan temel bileşenler şunlardır:

  • 📄 UserPermissionTest_CS_WinForms.csproj: net481 hedefleyen, Windows Forms etkinleştirilmiş ve Newtonsoft.Json bağımlılığı yüklenmiş SDK stili modern proje dosyası.
  • 📄 Program.cs: Uygulamanın ana giriş noktası.
  • 📄 User.cs: Kullanıcı adı, Ad Soyad, Parola (Hash formatında) ve İzin listesini barındıran veri sınıfı.
  • 📄 SessionManager.cs: Formlar arasında gerçek zamanlı olay bildirimleri (SessionStateChanged, UsersUpdated) sunan merkezi statik oturum yöneticisi.
  • 📄 PasswordHasher.cs: SHA-256 tek yönlü parola kriptolama ve doğrulama yardımcı sınıfı.
  • 🖥 MainForm:
    • MainForm.cs: Aktif oturum ve yetki durumu değişikliklerini dinleyen ana panel kodları.
    • MainForm.Designer.cs: Tasarım arayüzü ve yerleşim bileşenleri.
  • 🖥 LoginDialog:
  • 🖥 UserSettings:
    • UserSettings.cs: Kullanıcı listeleme, ekleme, silme ve dinamik izin tanımlama kodları. Maskelenmiş yönetici şifre düzenleme korumasını barındırır.
    • UserSettings.Designer.cs: Yan yana katalog ve profil giriş alanları.

🗄️ Depo Tasarım Deseni (Repository Pattern) & PostgreSQL Geçiş Yolu

Gelecekte uygulamanın SQL veritabanına taşınmasını kolaylaştırmak ve ölçeklenebilirlik sağlamak adına veri erişim katmanı tamamen Repository Deseni ile soyutlaştırılmıştır:

graph LR
    SessionManager -->|Kullanır| IUserRepository
    IUserRepository <|.. JsonUserRepository
    IUserRepository <|.. PostgreSqlUserRepository
    
    style IUserRepository fill:#1E293B,stroke:#F59E0B,stroke-width:2px,color:#fff
    style JsonUserRepository fill:#1E293B,stroke:#10B981,stroke-width:2px
    style PostgreSqlUserRepository fill:#1E293B,stroke:#0EA5E9,stroke-width:2px,stroke-dasharray: 5 5

Soyut Katmanlar:

  • IUserRepository.cs: Tanım arayüzüdür. LoadUsers, SaveUsers, LoadPermissions ve SavePermissions metot imzalarını içerir.
  • JsonUserRepository.cs: Dosya tabanlı (JSON) veri saklayıcıdır. Çıktı dizinindeki users.json ve permissions.json dosyalarını okur/yazar.

🐘 PostgreSQL Geçiş Adımları:

Veritabanı kurulumunuzu yaptığınızda yalnızca şu basit adımları izlemeniz yeterli olacaktır:

  1. Npgsql (PostgreSQL Client) ve EntityFramework veya Dapper kütüphanesini NuGet ile projenize yükleyin.
  2. IUserRepository arayüzünü uygulayan yeni bir repository sınıfı yazın:
    public class PostgreSqlUserRepository : IUserRepository
    {
        private readonly string _connectionString;
        public PostgreSqlUserRepository(string connString) => _connectionString = connString;
    
        public List<User> LoadUsers() { /* PostgreSQL SELECT sorgusu */ }
        public void SaveUsers(List<User> users) { /* PostgreSQL Kaydetme */ }
        public List<string> LoadPermissions() { /* DB yetki listesi sorgusu */ }
        public void SavePermissions(List<string> permissions) { /* DB yetki kaydı */ }
    }
    
  3. SessionManager.cs dosyasındaki tek satırı güncelleyin:
    // Eski JSON: private static readonly IUserRepository UserRepository = new JsonUserRepository();
    // Yeni PostgreSQL:
    private static readonly IUserRepository UserRepository = new PostgreSqlUserRepository("Host=localhost;Database=mydb;Username=postgres;Password=pwd");
    
  4. Sıfır Arayüz Değişikliği: MainForm, LoginDialog veya UserSettings formlarındaki tek bir satır kod dahi değiştirilmez. Uygulama verileri anında PostgreSQL üzerinden okuyup yazacaktır.

🔒 Rol Tabanlı Yetki Kontrolü (RBAC)

Uygulama, giriş yapan kullanıcının aktif izinlerine göre arayüzdeki işlemleri dinamik olarak kısıtlar:

  • Oturum Yokken (Kilitli Durum):
    • Kullanıcı yönetim butonu devre dışı kalır ve 🔒 Manage Users metniyle gösterilir.
  • Oturum Var Ancak İzin Yetersizken (Yetkisiz Durum):
    • Giriş yapan kullanıcının yetkileri arasında Manage Users veya Full Control yoksa:
      • Buton pasif kalır ve durum bilgisini belli etmek için 🔒 Manage Users (Locked) olarak güncellenir.
      • Tıklama olayında arka planda yetki kontrolü tekrarlanır ve yetkisiz erişim teşebbüslerinde güvenlik uyarısı verilir.
  • Oturum Var ve Yetki Yeterliyken (Yetkili Durum):
    • Kullanıcı yetkili ise buton anında aktifleşir, simgesi ve metni 👥 Manage Users olarak güncellenir ve tıklanabilir hale gelir.

🔐 Kriptografik Güvenlik & Parola Deneyimi (UX)

Uygulama üst düzey parola güvenliği standartları ve gelişmiş gizleme/gösterme yetenekleriyle donatılmıştır:

  • SHA-256 Tek Yönlü Kriptolama:
    • Şifreler diskte asla düz metin olarak saklanmaz. PasswordHasher.cs sınıfı, System.Security.Cryptography kütüphanesini kullanarak parolaları SHA-256 formatında şifreler.
  • Arka Planda Dinamik Otomatik Göç (Auto Hashing Migration):
    • JsonUserRepository dosya okuma aşamasında eski/açık metin parola kayıtları algılarsa, bunları arka planda otomatik olarak SHA-256 hash formatına dönüştürür ve diske güvenli şekilde geri yazar.
  • Güvenli Yönetim Ekranı Parola İşlemleri:
    • Kullanıcı detayları yüklendiğinde gerçek şifre hash'i arayüze gönderilmez; yerine ●●●●●●●● şeklinde güvenli bir maske gösterilir.
    • Şifre alanını ●●●●●●●● olarak bıraktığınızda sistem şifrenin değiştirilmediğini algılar ve mevcut hash'i aynen korur. Yeni bir şifre yazıldığında ise bunu şifreleyerek kaydeder.
  • Şifre Göster/Gizle Butonları (Eye Toggles):
    • LoginDialog ve UserSettings şifre kutularının sağına eklenen modern kenarlıksız göz butonu (btnTogglePassword ile 👁/🙈 durumları) şifrenin maskelenmesi '•' ve düz metin gösterilmesi arasında dinamik geçiş sağlar.

🎨 Görsel Tasarım Tercihleri

  • Özel Uyumlu Renk Paleti:
    • Üst Bilgi Panelleri: Modern Koyu Lacivert/Siyah (#1E293B)
    • Etkin Butonlar: İndigo Moru (#6366F1) ve Zümrüt Yeşili (#10B981)
    • Form Zeminleri: Beyaz (#FFFFFF) ve kontrast açık gri/slate dolgular (#F8FAFC, #F1F5F9)
  • Tipografi: Browser varsayılanları yerine temiz, okunaklılığı yüksek yarı kalın/kalın yapılandırılmış Segoe UI yazı tipleri kullanılmıştır.
  • Durum Bildirimleri: Oturum durumunu gösteren Yeşil/Kırmızı dinamik rozetler ve izin listesinde zengin onay sembolleri ().

🧪 Hazır Test Kullanıcı Bilgileri

Hızlı test işlemleri için sistem başlangıçta şu hesapları barındırır:

  1. Yönetici Kullanıcı (Tüm Yetkilere Sahip)

    • Kullanıcı Adı: admin
    • Parola: admin
    • Yetkileri: View Dashboard, Edit Settings, Manage Users, Full Control
  2. Standart Kullanıcı

    • Kullanıcı Adı: user
    • Parola: user
    • Yetkileri: View Dashboard