Skip to content

JWT Authentication

JSON Web Token (JWT) authentication in Moka.Auth provides a secure, stateless authentication mechanism for your API.

Configuration

Via appsettings.json

{
"Authentication": {
"EnableJWT": true
},
"Jwt": {
"Key": "your-secure-key-here-minimum-32-characters",
"Issuer": "your-application",
"Audience": "your-api",
"ExpirationMinutes": 30
}
}

Via Code

builder.Services.AddMokaAuth(options => {
options.EnableJWT = true;
options.JwtOptions = new JwtOptions {
Key = "your-secure-key-here-minimum-32-characters",
Issuer = "your-application",
Audience = "your-api",
ExpirationMinutes = 30
};
});

Usage

Authentication Controller

[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 });
}
}

Using the Token

Include the JWT in the Authorization header of your requests:

Authorization: Bearer <your-token-here>

Token Validation

Moka.Auth automatically validates:

  • Token signature
  • Expiration time
  • Issuer (if configured)
  • Audience (if configured)

Claims

The JWT token includes the following standard claims:

  • sub (Subject): User ID
  • name: Username
  • role: User roles
  • permission: User permissions
  • iat (Issued At): Token creation time
  • exp (Expiration Time): Token expiration time

Security Considerations

  1. Key Security:

    • Use a strong key (minimum 32 characters)
    • Store the key in secure configuration management
    • Rotate keys periodically
  2. Token Lifetime:

    • Set appropriate expiration time
    • Use refresh tokens for longer sessions
    • Implement token revocation if needed
  3. HTTPS:

    • Always use HTTPS in production
    • Set RequireHttpsMetadata = true in production

Advanced Configuration

Custom Token Configuration

builder.Services.AddMokaAuth(options => {
options.EnableJWT = true;
options.JwtOptions = new JwtOptions {
Key = configuration["Jwt:Key"],
Issuer = configuration["Jwt:Issuer"],
Audience = configuration["Jwt:Audience"],
ExpirationMinutes = 30,
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
RequireHttpsMetadata = true
};
});

Custom Claims

You can extend the token with custom claims by implementing IAuthService:

public class CustomAuthService : IAuthService
{
public async Task<AuthResult> AuthenticateAsync(string username, string password)
{
// Your authentication logic
var claims = new List<Claim>
{
new Claim("custom_claim", "value"),
// Add more custom claims
};
return await GenerateTokenAsync(user, claims);
}
}