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
                    
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="Nexttag.Auth.Jwt" Version="1.1.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Nexttag.Auth.Jwt" Version="1.1.2" />
                    
Directory.Packages.props
<PackageReference Include="Nexttag.Auth.Jwt" />
                    
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 Nexttag.Auth.Jwt --version 1.1.2
                    
#r "nuget: Nexttag.Auth.Jwt, 1.1.2"
                    
#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 Nexttag.Auth.Jwt@1.1.2
                    
#: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=Nexttag.Auth.Jwt&version=1.1.2
                    
Install as a Cake Addin
#tool nuget:?package=Nexttag.Auth.Jwt&version=1.1.2
                    
Install as a Cake Tool

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 contrato IJwtService (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)
  • IHttpContextAccessor
  • AddAuthentication(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:Key deve 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 AddKeycloakValidation ou AddNextAuthValidation depois de AddNexttagJwtAuth.
  • Nunca commite Jwt:Key em repositório — use dotnet user-secrets em dev e variável de ambiente em produção.
Product 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

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.

Version Downloads Last Updated
1.1.2 188 7/28/2026
1.1.0 153 7/28/2026
1.0.0 238 6/7/2026