Nexttag.Auth.Jwt
1.1.2
dotnet add package Nexttag.Auth.Jwt --version 1.1.2
NuGet\Install-Package Nexttag.Auth.Jwt -Version 1.1.2
<PackageReference Include="Nexttag.Auth.Jwt" Version="1.1.2" />
<PackageVersion Include="Nexttag.Auth.Jwt" Version="1.1.2" />
<PackageReference Include="Nexttag.Auth.Jwt" />
paket add Nexttag.Auth.Jwt --version 1.1.2
#r "nuget: Nexttag.Auth.Jwt, 1.1.2"
#:package Nexttag.Auth.Jwt@1.1.2
#addin nuget:?package=Nexttag.Auth.Jwt&version=1.1.2
#tool nuget:?package=Nexttag.Auth.Jwt&version=1.1.2
Nexttag.Auth.Jwt
Emissor de token local: gera e valida o seu próprio JWT (HMAC-SHA256), lê cookie HttpOnly e expõe
ICurrentUserProvider. É o dono do contratoIJwtService(emissão). Diferente dos provedores externos (Auth.Keycloak/Auth.NextAuth), que só validam tokens deles.
Instalar
dotnet add package Nexttag.Auth.Jwt
Requer .NET 10.
Registrar (Program.cs)
builder.Services.AddNexttagJwtAuth(builder.Configuration);
// ...
app.UseAuthentication();
app.UseAuthorization();
Registra automaticamente:
IJwtService→JwtService(scoped)ICurrentUserProvider→CurrentUserProvider(scoped)IHttpContextAccessorAddAuthentication(JwtBearer)+AddAuthorization()
Configurar
{
"Jwt": {
"Key": "<chave-secreta-minimo-32-chars>",
"Issuer": "https://api.seudominio.com.br",
"Audience": "meu-app",
"ExpirationMinutes": "480",
"CookieName": "meu_app_token"
}
}
| Chave | Obrigatório | Default |
|---|---|---|
Jwt:Key |
Sim | — |
Jwt:Issuer |
Sim | — |
Jwt:Audience |
Sim | — |
Jwt:ExpirationMinutes |
Não | 480 (8h) |
Jwt:CookieName |
Não | nextestoque_token |
O token é aceito tanto via header Authorization: Bearer <token> quanto via cookie HttpOnly com o nome configurado.
Usar
Gerar token (login)
public class AuthController(IJwtService jwt) : ControllerBase
{
[HttpPost("login")]
public IActionResult Login(LoginDto dto)
{
// valide credenciais aqui...
var token = jwt.GerarToken(user.Id, user.Email, user.Nome,
new Dictionary<string, string> { [ClaimTypes.Role] = "admin" });
// opção A: retornar no body
return Ok(new { token });
// opção B: gravar em cookie HttpOnly
Response.Cookies.Append("meu_app_token", token, new CookieOptions
{
HttpOnly = true, Secure = true, SameSite = SameSiteMode.Strict,
Expires = DateTimeOffset.UtcNow.AddMinutes(480),
});
return Ok();
}
}
Proteger endpoint
[Authorize]
[HttpGet("perfil")]
public IActionResult Perfil([FromServices] ICurrentUserProvider usuario)
=> Ok(new { usuario.UsuarioId, usuario.Nome, usuario.Email });
Ler claims customizadas
var tenantId = usuario.GetClaim("tenantId");
Receitas
Login completo com cookie + role:
var token = jwt.GerarToken(user.Id, user.Email!, user.Nome,
new Dictionary<string, string> { [ClaimTypes.Role] = user.Perfil });
Response.Cookies.Append("meu_app_token", token, new CookieOptions { HttpOnly = true, Secure = true });
return Ok(new { userId = user.Id, nome = user.Nome });
Endpoint somente para admins:
[Authorize(Roles = "admin")]
[HttpDelete("{id}")]
public async Task<IActionResult> Excluir(Guid id) { ... }
Renovar token (slide session):
// Reemita um token novo a partir do usuário autenticado
var novo = jwt.GerarToken(usuario.UsuarioId!.Value, usuario.Email!, usuario.Nome!);
Notas
Jwt:Keydeve ter no mínimo 32 caracteres (256 bits); chaves menores causam erro em runtime.ClockSkewéTimeSpan.Zero— tokens são inválidos imediatamente após a expiração.- Para aceitar tokens do Keycloak/NextAuth além dos locais, adicione
AddKeycloakValidationouAddNextAuthValidationdepois deAddNexttagJwtAuth. - Nunca commite
Jwt:Keyem repositório — usedotnet user-secretsem dev e variável de ambiente em produção.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. 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. |
-
net10.0
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 10.0.0)
- Nexttag.Auth (>= 1.1.0)
NuGet packages (2)
Showing the top 2 NuGet packages that depend on Nexttag.Auth.Jwt:
| Package | Downloads |
|---|---|
|
Nexttag.Auth.Identity.Google
Login social com Google para ASP.NET Identity (Nexttag.Auth.Identity): valida o id_token do Google, acha-ou-cria o usuario e emite JWT local. Sem Firebase. |
|
|
Nexttag.Auth.Identity
ASP.NET Identity integrado: login, registro, roles — banco local sem serviço externo |
GitHub repositories
This package is not used by any popular GitHub repositories.