AuthService.SDK 1.5.1

Suggested Alternatives

Criapix.Saas.Auth.SDK

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

AuthService SDK

NuGet Version NuGet Downloads GitHub Release License: MIT

SDK para integração com o AuthService - Sistema de Autenticação Única para SaaS. Fornece cliente HTTP completo, modelos de dados, extensões para dependency injection e middleware para autenticação JWT.

🚀 Instalação

Via NuGet Package Manager

dotnet add package AuthService.SDK

Via Package Manager Console

Install-Package AuthService.SDK

Via PackageReference (.csproj)

<PackageReference Include="AuthService.SDK" Version="1.1.0" />

⚙️ Configuração

1. appsettings.json

{
  "AuthService": {
    "BaseUrl": "https://your-auth-service.com",
    "SaasId": "12345678-1234-1234-1234-123456789012",
    "ApiKey": "your-api-key-optional",
    "TimeoutSeconds": 30
  },
  "Jwt": {
    "Secret": "your-jwt-secret-key",
    "Issuer": "AuthService",
    "Audience": "AuthServiceClients"
  }
}
Parâmetros de Configuração:
  • BaseUrl (obrigatório): URL base do AuthService
  • SaasId (obrigatório): Identificador único do seu SaaS
  • ApiKey (opcional): Chave de API para autenticação com o serviço
  • TimeoutSeconds (opcional): Timeout para requisições HTTP (padrão: 30s)

2. Program.cs / Startup.cs

using AuthService.SDK.Extensions;

var builder = WebApplication.CreateBuilder(args);

// ✅ Adiciona o cliente do AuthService
builder.Services.AddAuthService(builder.Configuration);

// ✅ Adiciona autenticação JWT (opcional, mas recomendado)
builder.Services.AddAuthServiceAuthentication(builder.Configuration);

// Outros serviços...
builder.Services.AddControllers();

var app = builder.Build();

// ✅ Configure o pipeline de autenticação
app.UseAuthentication();
app.UseAuthorization();

// Outros middlewares...
app.MapControllers();

app.Run();

📖 Uso

1. Autenticação de Usuários

using AuthService.SDK.Client;
using AuthService.SDK.Models;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
    private readonly IAuthServiceClient _authServiceClient;

    public AuthController(IAuthServiceClient authServiceClient)
    {
        _authServiceClient = authServiceClient;
    }

    [HttpPost("login")]
    public async Task<IActionResult> Login([FromBody] LoginRequest request)
    {
        try
        {
            var result = await _authServiceClient.LoginAsync(request);
            
            if (result.Success)
            {
                return Ok(new 
                { 
                    AccessToken = result.Data.AccessToken,
                    RefreshToken = result.Data.RefreshToken,
                    ExpiresAt = result.Data.ExpiresAt,
                    User = result.Data.User
                });
            }
            
            return BadRequest(new { Error = result.Error?.Message ?? "Login failed" });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { Error = ex.Message });
        }
    }

    [HttpPost("refresh")]
    public async Task<IActionResult> RefreshToken([FromBody] RefreshTokenRequest request)
    {
        var result = await _authServiceClient.RefreshTokenAsync(request);
        
        if (result.Success)
        {
            return Ok(result.Data);
        }
        
        return BadRequest(result.Error);
    }
}

2. Endpoints Protegidos

using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;

[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
    private readonly IAuthServiceClient _authServiceClient;

    public UserController(IAuthServiceClient authServiceClient)
    {
        _authServiceClient = authServiceClient;
    }

    [HttpGet("profile")]
    [Authorize] // 🔒 Endpoint protegido
    public async Task<IActionResult> GetProfile()
    {
        // Extrair dados do token JWT
        var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
        var saasId = User.FindFirst("saasId")?.Value;
        var email = User.FindFirst(ClaimTypes.Email)?.Value;
        
        if (Guid.TryParse(userId, out var userGuid))
        {
            var result = await _authServiceClient.GetUserByIdAsync(userGuid);
            
            if (result.Success)
            {
                return Ok(result.Data);
            }
        }
        
        return BadRequest("Invalid user");
    }

    [HttpGet("{id}")]
    [Authorize]
    public async Task<IActionResult> GetUser(Guid id)
    {
        var result = await _authServiceClient.GetUserByIdAsync(id);
        
        if (result.Success)
        {
            return Ok(result.Data);
        }
        
        return NotFound(result.Error?.Message);
    }
}

3. Gerenciamento de Usuários

[HttpPost("users")]
[Authorize]
public async Task<IActionResult> CreateUser([FromBody] CreateUserRequest request)
{
    var result = await _authServiceClient.CreateUserAsync(request);
    
    if (result.Success)
    {
        return Created($"/api/users/{result.Data.Id}", result.Data);
    }
    
    return BadRequest(result.Error);
}

[HttpPut("users/{id}")]
[Authorize]
public async Task<IActionResult> UpdateUser(Guid id, [FromBody] UpdateUserRequest request)
{
    var result = await _authServiceClient.UpdateUserAsync(id, request);
    
    if (result.Success)
    {
        return Ok(result.Data);
    }
    
    return BadRequest(result.Error);
}

[HttpGet("users/by-email/{email}")]
[Authorize]
public async Task<IActionResult> GetUserByEmail(string email)
{
    var result = await _authServiceClient.GetUserByEmailAsync(email);
    
    if (result.Success)
    {
        return Ok(result.Data);
    }
    
    return NotFound();
}

🚀 Funcionalidades

✅ Recursos Principais:

  • 🔐 Autenticação Completa: Login, logout, refresh tokens
  • 👤 Gerenciamento de Usuários: CRUD completo para usuários
  • 🔑 Validação JWT: Middleware automático para validação de tokens
  • 🏢 Multi-tenant: Suporte nativo a SaaS com isolamento por tenant
  • Performance: Cliente HTTP otimizado com timeout configurável
  • 🛡️ Segurança: Validação automática de tokens e headers

📋 Endpoints Disponíveis:

Método Endpoint Descrição
POST /auth/login Autenticar usuário
POST /auth/refresh Renovar token de acesso
GET /auth/verify Validar token atual
GET /users/{id} Buscar usuário por ID
GET /users/by-email/{email} Buscar usuário por email
POST /users Criar novo usuário
PUT /users/{id} Atualizar usuário
GET /health Health check do serviço

� Criação de Usuários com Senhas

Senha Crua (Padrão)

var createUserRequest = new CreateUserRequest
{
    Name = "João Silva",
    Email = "joao@exemplo.com",
    Password = "minhasenha123", // Senha será hasheada automaticamente
    IsPasswordHashed = false, // Padrão, pode ser omitido
    Role = UserRole.User,
    Phone = "11999999999",
    DocumentNumber = "12345678900"
};

var result = await _authServiceClient.CreateUserAsync(createUserRequest);

Senha Já Hasheada

var createUserRequest = new CreateUserRequest
{
    Name = "Maria Santos",
    Email = "maria@exemplo.com",
    Password = "$2a$11$...", // Hash BCrypt já calculado
    IsPasswordHashed = true, // Indica que a senha já está hasheada
    Role = UserRole.Admin
};

var result = await _authServiceClient.CreateUserAsync(createUserRequest);

⚠️ Importante: Quando IsPasswordHashed = true, certifique-se de que o hash da senha foi gerado usando BCrypt com os mesmos parâmetros do AuthService para garantir compatibilidade na validação.

�💡 Exemplo Completo de Serviço

using AuthService.SDK.Client;
using AuthService.SDK.Models;

public class UserAuthenticationService
{
    private readonly IAuthServiceClient _authClient;
    private readonly ILogger<UserAuthenticationService> _logger;

    public UserAuthenticationService(
        IAuthServiceClient authClient, 
        ILogger<UserAuthenticationService> logger)
    {
        _authClient = authClient;
        _logger = logger;
    }

    public async Task<LoginResponse> AuthenticateUserAsync(string email, string password)
    {
        try
        {
            var loginRequest = new LoginRequest
            {
                Email = email,
                Password = password
            };

            var response = await _authClient.LoginAsync(loginRequest);
            
            if (response.Success)
            {
                _logger.LogInformation("User {Email} authenticated successfully", email);
                return response.Data;
            }

            _logger.LogWarning("Authentication failed for {Email}: {Error}", 
                email, response.Error?.Message);
            
            throw new UnauthorizedAccessException(response.Error?.Message ?? "Login failed");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error during authentication for {Email}", email);
            throw;
        }
    }

    public async Task<UserDetailsResponse> GetUserProfileAsync(Guid userId)
    {
        var response = await _authClient.GetUserByIdAsync(userId);
        
        if (response.Success)
        {
            return response.Data;
        }

        throw new ArgumentException($"User not found: {response.Error?.Message}");
    }

    public async Task<bool> ValidateTokenAsync(string token)
    {
        try
        {
            var request = new ValidateTokenRequest { Token = token };
            var response = await _authClient.ValidateTokenAsync(request);
            
            return response.Success;
        }
        catch
        {
            return false;
        }
    }

    public async Task<bool> IsServiceHealthyAsync()
    {
        try
        {
            var response = await _authClient.GetHealthAsync();
            return response.Success;
        }
        catch
        {
            return false;
        }
    }
}

🔧 Modelos de Dados

LoginRequest

public class LoginRequest
{
    public string Email { get; set; }
    public string Password { get; set; }
    public string SaasId { get; set; } // Preenchido automaticamente
}

LoginResponse

public class LoginResponse
{
    public string AccessToken { get; set; }
    public string RefreshToken { get; set; }
    public DateTime ExpiresAt { get; set; }
    public UserDetailsResponse User { get; set; }
}

UserDetailsResponse

public class UserDetailsResponse
{
    public Guid Id { get; set; }
    public string Email { get; set; }
    public string Name { get; set; }
    public string SaasId { get; set; }
    public DateTime CreatedAt { get; set; }
    public DateTime? UpdatedAt { get; set; }
    public bool IsActive { get; set; }
}

🛠️ Desenvolvimento

Estrutura do Projeto

AuthService.SDK/
├── Client/
│   ├── IAuthServiceClient.cs      # Interface do cliente
│   └── AuthServiceClient.cs       # Implementação do cliente HTTP
├── Models/
│   ├── LoginRequest.cs            # Modelo de requisição de login
│   ├── LoginResponse.cs           # Modelo de resposta de login
│   ├── UserDetailsResponse.cs     # Modelo de usuário
│   └── ApiResponse.cs             # Modelo de resposta da API
├── Configuration/
│   └── AuthServiceOptions.cs      # Opções de configuração
├── Extensions/
│   └── ServiceCollectionExtensions.cs # Extensões para DI
└── Middleware/
    └── AuthServiceMiddleware.cs    # Middleware de autenticação

Requisitos

  • .NET 9.0 ou superior
  • Microsoft.AspNetCore.Authentication.JwtBearer 9.0.0+
  • Microsoft.Extensions.Http 9.0.0+

📄 Licença

Este projeto está licenciado sob a Licença MIT.

🤝 Contribuição

Contribuições são bem-vindas! Por favor, abra uma issue ou pull request no repositório oficial.

📞 Suporte

Para suporte técnico, entre em contato através do GitHub Issues ou envie um email para: support@predin.com


Desenvolvido com ❤️ pela equipe Predin

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  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.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.5.1 276 9/26/2025 1.5.1 is deprecated because it is no longer maintained.
1.5.0 223 9/26/2025
1.4.5 206 9/23/2025
1.4.4 256 9/19/2025
1.4.1 325 9/19/2025
1.3.7 332 9/17/2025
1.3.6 331 9/17/2025
1.3.5 334 9/16/2025
1.3.4 324 9/16/2025
1.3.3 338 9/16/2025
1.3.2 336 9/16/2025
1.1.0 165 9/12/2025

Versão 1.4.0 - NOVO CAMPO: Adicionado campo IsPasswordHashed no CreateUserRequest para especificar se a senha já está hasheada (padrão: false para senha crua).