FastTechFoodsAuth.Security
1.0.4
dotnet add package FastTechFoodsAuth.Security --version 1.0.4
NuGet\Install-Package FastTechFoodsAuth.Security -Version 1.0.4
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="FastTechFoodsAuth.Security" Version="1.0.4" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="FastTechFoodsAuth.Security" Version="1.0.4" />
<PackageReference Include="FastTechFoodsAuth.Security" />
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 FastTechFoodsAuth.Security --version 1.0.4
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: FastTechFoodsAuth.Security, 1.0.4"
#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 FastTechFoodsAuth.Security@1.0.4
#: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=FastTechFoodsAuth.Security&version=1.0.4
#tool nuget:?package=FastTechFoodsAuth.Security&version=1.0.4
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
FastTechFoodsAuth.Security
Biblioteca compartilhada para autenticação JWT padronizada nos projetos FastTechFoods.
✨ Funcionalidades
- ✅ Configuração automática de autenticação JWT
- ✅ Validação robusta de configurações
- ✅ Swagger integrado com JWT Bearer
- ✅ Middleware de auditoria de segurança
- ✅ Logging detalhado de eventos de autenticação
- ✅ Mensagens de erro amigáveis
- ✅ Suporte a variáveis de ambiente para secrets
🚀 Uso Rápido
1. Instalar o pacote
dotnet add package FastTechFoodsAuth.Security
2. Configurar no appsettings.json
{
"Jwt": {
"Key": "sua-chave-super-secreta-de-pelo-menos-32-caracteres",
"Issuer": "FastTechFoods.Auth",
"Audience": "FastTechFoods.Apps",
"ExpirationHours": 24
}
}
3. Configurar no Program.cs
using FastTechFoodsAuth.Security.Extensions;
var builder = WebApplication.CreateBuilder(args);
// ✨ Uma linha para configurar toda a autenticação JWT!
builder.Services.AddFastTechFoodsJwtAuthentication(builder.Configuration);
// ✨ Uma linha para configurar Swagger com JWT!
builder.Services.AddFastTechFoodsSwaggerWithJwt("Minha API");
var app = builder.Build();
// ✨ Middleware de auditoria de segurança (opcional)
app.UseFastTechFoodsSecurityAudit();
app.UseAuthentication();
app.UseAuthorization();
app.Run();
🔐 Segurança
Variáveis de Ambiente
Para máxima segurança, defina a chave JWT via variável de ambiente:
export JWT_SECRET="sua-chave-super-secreta-de-pelo-menos-32-caracteres"
Validações Automáticas
- ✅ Chave mínima de 256 bits (32 caracteres)
- ✅ Issuer e Audience obrigatórios
- ✅ Validação de expiração
- ✅ Assinatura obrigatória
- ✅ Clock skew configurável
📊 Logging
A biblioteca fornece logging detalhado de todos os eventos de segurança:
[13:45:20 WRN] Falha na autenticação JWT: The token is expired | Path: /api/protected | IP: 192.168.1.100
[13:45:25 WRN] Tentativa de acesso não autorizado: GET /api/admin | IP: 192.168.1.100 | HasAuthHeader: False
⚙️ Configuração Avançada
builder.Services.AddFastTechFoodsJwtAuthentication(
builder.Configuration,
options =>
{
options.ExpirationHours = 8; // Override para 8 horas
options.ClockSkew = TimeSpan.FromMinutes(5); // Tolerância de 5 minutos
});
🔄 Migração de Projeto Existente
Antes (código repetitivo):
// 50+ linhas de configuração JWT repetidas em cada projeto
var jwtSecret = Environment.GetEnvironmentVariable("JWT_SECRET") ?? ...
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
builder.Services.AddAuthentication(options => { ... })
.AddJwtBearer(options => { ... });
// ... mais configurações
Depois (simples e padronizado):
// 1 linha que faz tudo!
builder.Services.AddFastTechFoodsJwtAuthentication(builder.Configuration);
📦 Reutilização
Esta biblioteca pode ser usada em:
- ✅ APIs FastTechFoods
- ✅ Microserviços
- ✅ Gateways
- ✅ Qualquer aplicação ASP.NET Core
🛠️ Desenvolvimento
Para contribuir ou modificar a biblioteca:
- Clone o repositório
- Faça suas alterações
- Aumente a versão no
.csproj - Execute
dotnet packpara gerar o NuGet - Publique o pacote
📝 Exemplos de Uso
Veja os projetos de exemplo na pasta /examples para casos de uso específicos.
| Product | Versions 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.
-
net9.0
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 9.0.0)
- Microsoft.Extensions.Configuration.Abstractions (>= 9.0.0)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 9.0.0)
- Swashbuckle.AspNetCore (>= 6.6.2)
- System.IdentityModel.Tokens.Jwt (>= 8.2.1)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.