Skip to content

Quick Start Guide

This guide will help you quickly implement authentication in your .NET application using Moka.Auth.

Basic Setup with SQLite

  1. Configure Moka.Auth in your Program.cs:
var builder = WebApplication.CreateBuilder(args);
// Configure Moka.Auth with SQLite
builder.Services.AddMokaAuthDbContext(dbOptions =>
{
dbOptions.ConnectionString = "Data Source=moka.db";
dbOptions.DbType = DbType.SQLite;
dbOptions.AutoMigrate = true;
});
// Add JWT authentication (Option 1: Automatic configuration from appsettings.json)
builder.Services.AddMokaAuth();
// Configure authorization
builder.Services.AddMokaAuthorization();
var app = builder.Build();
// Configure the HTTP request pipeline
app.UseHttpsRedirection();
app.UseMokaAuthDatabase();
app.UseMokaAuth(builder.Configuration);

Using Built-in Endpoints

Moka.Auth provides built-in endpoints that you can easily enable:

// Map authentication endpoints
app.MapMokaDefaultEndpoints(options =>
{
options.EnableAuthEndpoints = true; // /auth/login, /auth/refresh, etc.
options.EnableUserEndpoints = true; // /users/*
options.EnableRoleEndpoints = true; // /roles/*
options.EnablePermissionEndpoints = true; // /permissions/*
options.EnableApiKeyEndpoints = true; // /apikeys/*
});

You can also selectively enable only the endpoints you need:

app.MapMokaDefaultEndpoints(options =>
{
options.EnableAuthEndpoints = true; // Enable only authentication endpoints
options.EnableUserEndpoints = false; // Disable user management
options.EnableRoleEndpoints = false; // Disable role management
options.EnablePermissionEndpoints = false; // Disable permission management
options.EnableApiKeyEndpoints = false; // Disable API key management
});

Data Seeding Options

Moka.Auth provides multiple ways to seed your authentication data:

1. Default Configuration

await app.SeedMokaAuthDataAsync();

2. Environment Variables

await app.SeedMokaAuthDataFromEnvironmentAsync();

3. JSON Configuration

var jsonFilePath = Path.Combine(app.Environment.ContentRootPath, "seed-data.json");
await app.SeedMokaAuthDataFromJsonAsync(jsonFilePath);

4. YAML Configuration

var yamlFilePath = Path.Combine(app.Environment.ContentRootPath, "seed-data.yaml");
await app.SeedMokaAuthDataFromYamlAsync(yamlFilePath);

5. Programmatic Configuration

await app.SeedMokaAuthDataAsync(new MokaAuthSeederOptions
{
Users =
[
new UserSeedConfiguration()
{
Username = "admin",
Email = "[email protected]",
Password = Environment.GetEnvironmentVariable("MOKA_AUTH_ADMIN_PASSWORD") ?? "Admin123!",
FirstName = "System",
LastName = "Administrator",
IsActive = true,
EmailConfirmed = true,
Roles = ["Admin"],
ApiKeys = ["AdminApiKey"]
},
new UserSeedConfiguration()
{
Username = "api",
Email = "[email protected]",
Password = Environment.GetEnvironmentVariable("MOKA_AUTH_API_PASSWORD") ?? "Api123!",
FirstName = "API",
LastName = "Service",
IsActive = true,
EmailConfirmed = true,
Roles = ["User"],
Permissions = ["ApiKeys:Manage"],
ApiKeys = ["ServiceApiKey"]
}
],
ApiKeys =
[
new ApiKeySeedConfiguration()
{
Name = "AdminMasterKey",
Value = Environment.GetEnvironmentVariable("MOKA_AUTH_ADMIN_API_KEY"),
Username = "admin",
ExpiresAt = DateTimeOffset.UtcNow.AddYears(1)
}
],
UseTransaction = true, // Use transaction for safety
ThrowOnError = false, // Don't throw on error, just log it
RecreateDefaults = false // Don't update existing entities
});

Custom Implementation

If you prefer not to use the built-in endpoints, you can create your own controllers:

[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
private readonly IAuthService _authService;
public AuthController(IAuthService authService)
{
_authService = authService;
}
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] LoginRequest request)
{
var result = await _authService.AuthenticateAsync(request.Username, request.Password);
if (!result.Succeeded)
return Unauthorized(result.Error);
return Ok(new { Token = result.Token });
}
}

Protecting Endpoints

Using Built-in Attributes

[ApiController]
[Route("api/[controller]")]
public class SecureController : ControllerBase
{
[Authorize] // Requires authentication
[HttpGet]
public IActionResult Get() => Ok("Authenticated!");
[Authorize(Roles = "Admin")] // Requires Admin role
[HttpGet("admin")]
public IActionResult AdminOnly() => Ok("Admin only!");
[RequirePermission("users.read")] // Requires specific permission
[HttpGet("users")]
public IActionResult UsersOnly() => Ok("Has users.read permission!");
}

Next Steps