Convex-addisalem.Shared.Security 1.0.0

dotnet add package Convex-addisalem.Shared.Security --version 1.0.0
                    
NuGet\Install-Package Convex-addisalem.Shared.Security -Version 1.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Convex-addisalem.Shared.Security" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Convex-addisalem.Shared.Security" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Convex-addisalem.Shared.Security" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Convex-addisalem.Shared.Security --version 1.0.0
                    
#r "nuget: Convex-addisalem.Shared.Security, 1.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Convex-addisalem.Shared.Security@1.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Convex-addisalem.Shared.Security&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Convex-addisalem.Shared.Security&version=1.0.0
                    
Install as a Cake Tool

Convex.Shared.Security

Security and authentication utilities for Convex microservices.

Features

  • JWT Authentication: JWT token generation and validation
  • API Key Management: Service-to-service authentication
  • Password Hashing: Secure password hashing with salt
  • CORS Configuration: Cross-origin resource sharing setup
  • Rate Limiting: Built-in rate limiting support
  • Secure Random: Cryptographically secure random string generation

Installation

<PackageReference Include="Convex.Shared.Security" Version="1.0.0" />

Quick Start

1. Register Services

// In Program.cs
services.AddConvexSecurity(options =>
{
    options.JwtSecret = "your-jwt-secret-key";
    options.JwtIssuer = "Convex";
    options.JwtAudience = "ConvexUsers";
});

2. Use in Your Service

public class AuthService
{
    private readonly IConvexSecurityService _securityService;

    public AuthService(IConvexSecurityService securityService)
    {
        _securityService = securityService;
    }

    public async Task<string> LoginAsync(string email, string password)
    {
        // Validate user credentials
        var user = await _userRepository.GetByEmailAsync(email);
        if (user == null || !_securityService.VerifyPassword(password, user.PasswordHash))
        {
            throw new UnauthorizedAccessException("Invalid credentials");
        }

        // Generate JWT token
        var token = _securityService.GenerateJwtToken(
            user.Id.ToString(), 
            user.Email, 
            user.Roles.ToArray());

        return token;
    }
}

JWT Authentication

Generate JWT Token

var token = _securityService.GenerateJwtToken(
    userId: "123",
    email: "user@example.com",
    roles: new[] { "User", "Admin" },
    expiresInMinutes: 60);

Validate JWT Token

if (_securityService.ValidateJwtToken(token))
{
    var claims = _securityService.GetClaimsFromToken(token);
    var userId = claims?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
}

Configure JWT Authentication

services.AddConvexJwtAuthentication(options =>
{
    options.JwtSecret = "your-jwt-secret-key";
    options.JwtIssuer = "Convex";
    options.JwtAudience = "ConvexUsers";
});

API Key Authentication

Generate API Key

var apiKey = _securityService.GenerateApiKey(
    serviceName: "UserService",
    expiresAt: DateTime.UtcNow.AddDays(30));

Validate API Key

if (_securityService.ValidateApiKey(apiKey))
{
    var keyInfo = _securityService.GetApiKeyInfo(apiKey);
    var serviceName = keyInfo?.ServiceName;
}

Configure API Key Authentication

services.AddConvexApiKeyAuthentication(options =>
{
    options.ApiKeySecret = "your-api-key-secret";
});

Password Security

Hash Password

var hashedPassword = _securityService.HashPassword("userPassword123");

Verify Password

if (_securityService.VerifyPassword("userPassword123", hashedPassword))
{
    // Password is correct
}

CORS Configuration

services.AddConvexCors(options =>
{
    options.AllowedOrigins = new[] { "https://app.convex.com", "https://admin.convex.com" };
});

Configuration

appsettings.json

{
  "ConvexSecurity": {
    "JwtSecret": "your-jwt-secret-key-here",
    "JwtIssuer": "Convex",
    "JwtAudience": "ConvexUsers",
    "JwtExpirationMinutes": 60,
    "ApiKeySecret": "your-api-key-secret",
    "PasswordHashIterations": 100000,
    "RequireHttps": true,
    "AllowedOrigins": [
      "https://app.convex.com",
      "https://admin.convex.com"
    ],
    "RateLimit": {
      "Enabled": true,
      "MaxRequestsPerMinute": 100,
      "MaxRequestsPerHour": 1000,
      "MaxRequestsPerDay": 10000
    }
  }
}

Environment Variables

export CONVEX_JWT_SECRET="your-jwt-secret-key"
export CONVEX_JWT_ISSUER="Convex"
export CONVEX_JWT_AUDIENCE="ConvexUsers"
export CONVEX_API_KEY_SECRET="your-api-key-secret"

Security Best Practices

JWT Security

  1. Use Strong Secrets: Use cryptographically strong secrets
  2. Short Expiration: Use short token expiration times
  3. HTTPS Only: Always use HTTPS in production
  4. Validate Claims: Always validate token claims

API Key Security

  1. Rotate Keys: Regularly rotate API keys
  2. Monitor Usage: Monitor API key usage
  3. Set Expiration: Set expiration dates for API keys
  4. Secure Storage: Store API keys securely

Password Security

  1. Strong Hashing: Use strong hashing algorithms
  2. Salt: Always use salt for password hashing
  3. Iterations: Use sufficient iterations for PBKDF2
  4. Validation: Implement password strength validation

Rate Limiting

services.AddConvexSecurity(options =>
{
    options.RateLimit.Enabled = true;
    options.RateLimit.MaxRequestsPerMinute = 100;
    options.RateLimit.MaxRequestsPerHour = 1000;
    options.RateLimit.MaxRequestsPerDay = 10000;
});

Secure Random Generation

// Generate secure random string
var randomString = _securityService.GenerateSecureRandomString(32);

// Generate secure random bytes
var randomBytes = new byte[32];
using var rng = RandomNumberGenerator.Create();
rng.GetBytes(randomBytes);

License

This project is licensed under the MIT License.

Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0 99 10/17/2025

Initial release of Convex.Shared.Security