September 26, 20258 min readBy Prithivi Kai Balaji

Google Authenticator - Two-Factor Authentication Web Application

ASP.NET MVCTwo-Factor AuthenticationGoogle AuthenticatorTOTPSecurityBootstrap

Google Authenticator - Two-Factor Authentication Web Application


A secure ASP.NET MVC web application that implements Google Authenticator-style two-factor authentication (2FA) for enhanced login security.


🔐 Features


  • Two-Factor Authentication: Implements TOTP (Time-based One-Time Password) using Google Authenticator
  • QR Code Generation: Automatically generates QR codes for easy setup with authenticator apps
  • Manual Setup: Provides manual entry keys for authenticator app configuration
  • Session Management: Secure session handling with Forms Authentication
  • Cookie-based Remember: Optional "remember device" functionality using secure cookies
  • Bootstrap UI: Modern, responsive user interface using Bootstrap 4
  • Configurable: Easy configuration through web.config settings

  • 🚀 Quick Start


    Prerequisites


  • Visual Studio 2019 or later
  • .NET Framework 4.6.1 or later
  • IIS Express (included with Visual Studio)

  • Installation


    1. Clone the repository

    BASH
       git clone https://github.com/Prithivi-au/GoogleAuthenticator.git
       cd GoogleAuthenticator
    

    2. Open in Visual Studio

    - Open GAuthenticator.sln in Visual Studio

    - Restore NuGet packages (right-click solution → Restore NuGet Packages)


    3. Configure the application

    - Open Web.config

    - Update the following settings in :

    XML
       <add key="GAuthPrivateKey" value="YOUR_SECRET_KEY_HERE"/>
       <add key="GAuthEnable" value="1"/>
    

    4. Run the application

    - Press F5 or click "Start Debugging"

    - Navigate to http://localhost:port/Login/Login


    Default Login Credentials


  • Username: TestUser
  • Password: 12345

  • > ⚠️ Important: Change these credentials in production!


    📱 How to Use


    First-Time Setup


    1. Login with your credentials

    2. Scan QR Code with your authenticator app (Google Authenticator, Authy, etc.)

    3. Enter Verification Code from your authenticator app

    4. Access Protected Area - you're now logged in with 2FA enabled


    Supported Authenticator Apps


  • Google Authenticator
  • Microsoft Authenticator
  • Authy
  • Any TOTP-compatible authenticator app

  • 🛠️ Configuration


    Web.config Settings


    XML
    <appSettings>
      <!-- Your secret key for generating unique user keys -->
      <add key="GAuthPrivateKey" value="YOUR_SECRET_KEY_HERE"/>
      
      <!-- Enable/disable 2FA (1 = enabled, 0 = disabled) -->
      <add key="GAuthEnable" value="1"/>
    </appSettings>
    

    Security Considerations


    1. Change Default Credentials: Update the hardcoded username/password in LoginController.cs

    2. Use Strong Secret Key: Generate a strong, random secret key for GAuthPrivateKey

    3. Enable HTTPS: Always use HTTPS in production

    4. Database Integration: Replace hardcoded credentials with database authentication


    🔧 Technical Details


    Technologies Used


  • Framework: ASP.NET MVC 5
  • Target Framework: .NET Framework 4.6.1
  • Authentication: Forms Authentication
  • 2FA Library: Google.Authenticator NuGet package
  • UI Framework: Bootstrap 4
  • JavaScript: jQuery 3.4.1

  • Key Components


    1. TwoFactorAuthenticator: Core 2FA functionality

    2. QR Code Generation: Automatic QR code creation for easy setup

    3. Session Management: Secure session handling

    4. Cookie-based Remember: Optional device remembering


    Authentication Flow


    1. User enters username/password

    2. System validates credentials

    3. If 2FA is enabled:

    - Generate unique key for user

    - Display QR code for authenticator app setup

    - Validate TOTP code from authenticator app

    - Set authentication cookie if valid

    4. Redirect to protected area


    💻 Sample Code


    Two-Factor Authentication Setup


    CSHARP
    public class TwoFactorService
    {
        public TwoFactorSetupResult SetupTwoFactor(string username, string password)
        {
            // Validate credentials
            if (username == "prithivi" && password == "12345")
            {
                // Check if 2FA is enabled
                if (ConfigurationManager.AppSettings["GAuthEnable"] == "1")
                {
                    // Check if user has already set up 2FA
                    if (!HasExistingTwoFactorSetup(username))
                    {
                        // Generate QR code for 2FA setup
                        string userSecretKey = username + ConfigurationManager.AppSettings["GAuthPrivateKey"];
                        byte[] userUniqueKey = Encoding.ASCII.GetBytes(userSecretKey);
                        
                        TwoFactorAuthenticator TwoFacAuth = new TwoFactorAuthenticator();
                        var setupInfo = TwoFacAuth.GenerateSetupCode("MyApp", username, userUniqueKey, 3, true);
                        
                        return new TwoFactorSetupResult
                        {
                            Success = true,
                            QrCodeUrl = setupInfo.QrCodeSetupImageUrl,
                            ManualEntryKey = setupInfo.ManualEntryKey,
                            UserSecretKey = userSecretKey
                        };
                    }
                    else
                    {
                        return new TwoFactorSetupResult { Success = true, AlreadySetup = true };
                    }
                }
            }
            
            return new TwoFactorSetupResult { Success = false };
        }
        
        private bool HasExistingTwoFactorSetup(string username)
        {
            // Check if user has existing 2FA setup
            return false; // Implement your logic here
        }
    }
    

    TOTP Code Validation


    CSHARP
    public class TwoFactorValidationService
    {
        public ValidationResult ValidateTwoFactorCode(string code, string userSecretKey)
        {
            TwoFactorAuthenticator TwoFacAuth = new TwoFactorAuthenticator();
            byte[] userUniqueKey = Encoding.ASCII.GetBytes(userSecretKey);
            
            bool isValid = TwoFacAuth.ValidateTwoFactorPIN(userUniqueKey, code);
    
            if (isValid)
            {
                // Store successful validation
                StoreTwoFactorSuccess(userSecretKey);
                
                return new ValidationResult
                {
                    Success = true,
                    Message = "Authentication successful"
                };
            }
            
            return new ValidationResult
            {
                Success = false,
                Message = "Invalid code"
            };
        }
        
        private void StoreTwoFactorSuccess(string userSecretKey)
        {
            // Implement your storage logic here
            // Could be database, cache, or session
        }
    }
    
    public class ValidationResult
    {
        public bool Success { get; set; }
        public string Message { get; set; }
    }
    
    public class TwoFactorSetupResult
    {
        public bool Success { get; set; }
        public string QrCodeUrl { get; set; }
        public string ManualEntryKey { get; set; }
        public string UserSecretKey { get; set; }
        public bool AlreadySetup { get; set; }
    }
    

    Web.config Configuration


    XML
    <configuration>
      <appSettings>
        <!-- Your secret key for generating unique user keys -->
        <add key="GAuthPrivateKey" value="YOUR_SECRET_KEY_HERE"/>
        
        <!-- Enable/disable 2FA (1 = enabled, 0 = disabled) -->
        <add key="GAuthEnable" value="1"/>
      </appSettings>
      
      <system.web>
        <authentication mode="Forms">
          <forms loginUrl="~/Login/Login" timeout="2880"/>
        </authentication>
        
        <compilation debug="true" targetFramework="4.6.1"/>
        <httpRuntime targetFramework="4.6.1"/>
      </system.web>
    </configuration>
    

    NuGet Package Installation


    XML
    <!-- packages.config -->
    <packages>
      <package id="GoogleAuthenticator" version="3.0.0" targetFramework="net461" />
      <package id="Microsoft.AspNet.Mvc" version="5.2.7" targetFramework="net461" />
      <package id="Microsoft.AspNet.WebPages" version="3.2.7" targetFramework="net461" />
      <package id="Microsoft.AspNet.Razor" version="3.2.7" targetFramework="net461" />
      <package id="Newtonsoft.Json" version="12.0.2" targetFramework="net461" />
    </packages>
    

    🚀 Deployment


    IIS Deployment


    1. Build the application in Release mode

    2. Publish to a folder

    3. Copy files to IIS web directory

    4. Configure IIS application pool for .NET Framework 4.6.1

    5. Update web.config with production settings


    Azure Deployment


    1. Create an Azure App Service

    2. Configure for .NET Framework 4.6.1

    3. Deploy using Visual Studio or Azure DevOps

    4. Update connection strings and app settings


    🔒 Security Features


  • TOTP Algorithm: Industry-standard time-based one-time passwords
  • Unique User Keys: Each user gets a unique secret key
  • Session Security: Secure session management
  • Forms Authentication: Built-in ASP.NET authentication
  • HTTPS Ready: Configured for secure communication

  • 📝 Customization


    Database Integration


    Replace hardcoded credentials with database authentication:


    CSHARP
    // Example with Entity Framework
    var user = db.Users.FirstOrDefault(u => u.Username == login.UserName);
    if (user != null && VerifyPassword(login.Password, user.PasswordHash))
    {
        // Authentication logic here
    }
    

    Custom Styling


    Modify CSS files in the Content/ directory to match your brand.


    🤝 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


    🙏 Acknowledgments


  • Google Authenticator Library for TOTP implementation
  • Bootstrap for UI components
  • jQuery for JavaScript functionality

  • 📞 Support


    If you have any questions or need help with this project, please open an issue on GitHub or contact the maintainer.

    Security Features

    TOTP Algorithm

    Industry-standard time-based one-time passwords

    Unique User Keys

    Each user gets a unique secret key

    Session Security

    Secure session management with Forms Authentication

    HTTPS Ready

    Configured for secure communication

    Google Authenticator Project

    Get the complete ASP.NET MVC source code, configuration examples, and deployment guides for implementing Google Authenticator-style two-factor authentication.

    View on GitHub