Elvia.Elvid.TokenClient 1.5.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package Elvia.Elvid.TokenClient --version 1.5.0
                    
NuGet\Install-Package Elvia.Elvid.TokenClient -Version 1.5.0
                    
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="Elvia.Elvid.TokenClient" Version="1.5.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Elvia.Elvid.TokenClient" Version="1.5.0" />
                    
Directory.Packages.props
<PackageReference Include="Elvia.Elvid.TokenClient" />
                    
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 Elvia.Elvid.TokenClient --version 1.5.0
                    
#r "nuget: Elvia.Elvid.TokenClient, 1.5.0"
                    
#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 Elvia.Elvid.TokenClient@1.5.0
                    
#: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=Elvia.Elvid.TokenClient&version=1.5.0
                    
Install as a Cake Addin
#tool nuget:?package=Elvia.Elvid.TokenClient&version=1.5.0
                    
Install as a Cake Tool

Elvia.Elvid.TokenClient

OAuth2 Client Credentials bibliotek for Elvid med automatisk token-håndtering og caching.

Erstatter IdentityModel avhengigheter og duplikat ElvidAccessTokenService kode.

Kom i gang

1. Installer

dotnet add package Elvia.Elvid.TokenClient

2. Konfigurer

// Forutsetter eksisterende Vault-konfigurasjon (AddHashiVaultSecrets)
builder.Services.AddElvidTokenProvider(options =>
{
    options.TokenEndpoint = builder.Configuration.EnsureHasValue("system:kv:elvid:tokenendpoint");
    options.ClientId = builder.Configuration.EnsureHasValue("system:kv:elvid:clientid");
    options.ClientSecret = builder.Configuration.EnsureHasValue("system:kv:elvid:clientsecret");
});

💡 Tip: TokenEndpoint er anbefalt over Authority (discovery) - enklere, raskere og mer robust.

3. Bruk

HttpClient (anbefalt):

// Default provider
builder.Services.AddHttpClient("ExternalApi", client =>
{
    client.BaseAddress = new Uri("https://api.elvia.no/");
})
.AddElvidAuthHandler(); // Automatisk Bearer token fra default provider

// Named provider (for multiple clients)
builder.Services.AddHttpClient("KumaApi", client =>
{
    client.BaseAddress = new Uri("https://kuma.elvia.io/");
})
.AddElvidAuthHandler("kuma"); // Bruker navngitt "kuma" provider

// I service:
var client = _httpClientFactory.CreateClient("ExternalApi");
var response = await client.GetAsync("endpoint"); // Token legges til automatisk

Direkte (Client Credentials):

public class MyService
{
    private readonly IElvidTokenProvider _tokenProvider;
    
    public async Task<string> GetTokenAsync()
    {
        return await _tokenProvider.GetAccessTokenAsync([]);
    }
}

Password Grant (for testing/smoketests):

public class MySmokeTestService
{
    private readonly IElvidTokenProvider _tokenProvider;
    
    public async Task<string> GetUserTokenAsync()
    {
        return await _tokenProvider.GetAccessTokenAsync("testuser", "testpass", []);
    }
}

Standalone bruk (uten Dependency Injection):

// Perfect for smoketests og enkle skript
var tokenProvider = ElvidTokenClientFactory.Create(
    "https://elvid.test-elvia.io/connect/token",
    "your-client-id",
    "your-client-secret");

// Client credentials
var token = await tokenProvider.GetAccessTokenAsync([]);

// Password grant
var userToken = await tokenProvider.GetAccessTokenAsync("testuser", "testpass", []);

Multiple API clients (anbefalt for større systemer):

// Registrer flere navngitte clients
builder.Services.AddElvidTokenProvider("convey", options =>
{
    options.TokenEndpoint = builder.Configuration.EnsureHasValue("elvid:kv:elvid:elvid-convey:tokenendpoint");
    options.ClientId = builder.Configuration.EnsureHasValue("elvid:kv:elvid:elvid-convey:clientid");
    options.ClientSecret = builder.Configuration.EnsureHasValue("elvid:kv:elvid:elvid-convey:clientsecret");
});

builder.Services.AddElvidTokenProvider("kuma", options =>
{
    options.TokenEndpoint = builder.Configuration.EnsureHasValue("elvid:kv:elvid:elvid-kuma:tokenendpoint");
    options.ClientId = builder.Configuration.EnsureHasValue("elvid:kv:elvid:elvid-kuma:clientid");
    options.ClientSecret = builder.Configuration.EnsureHasValue("elvid:kv:elvid:elvid-kuma:clientsecret");
});

// I service - bruk factory til å få riktig client
public class MyService
{
    private readonly IElvidTokenProviderFactory _tokenProviderFactory;

    public async Task CallConveyAsync()
    {
        var conveyProvider = _tokenProviderFactory.GetProvider("convey");
        var token = await conveyProvider.GetAccessTokenAsync([]);
        // Use token for Convey API calls
    }
    
    public async Task CallKumaAsync()
    {
        var kumaProvider = _tokenProviderFactory.GetProvider("kuma");
        var token = await kumaProvider.GetAccessTokenAsync([]);
        // Use token for Kuma API calls
    }
}

Migration fra IdentityModel

Problem: KubernetesClient vulnerability krever oppgradering av Elvia.Configuration, som fjerner IdentityModel avhengigheter.

Løsning: Erstatt IdentityModel med TokenClient.

SetBearerToken Extension Method

TokenClient inkluderer SetBearerToken extension method for enkel migrering:

using Elvia.Elvid.TokenClient.Http;

// Fungerer akkurat som IdentityModel sin SetBearerToken
var token = await _tokenProvider.GetAccessTokenAsync([]);
httpClient.SetBearerToken(token);

Før (IdentityModel - fungerer ikke lenger):

// Krever IdentityModel pakke som ikke lenger er inkludert
var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
{
    Address = "https://elvid.test-elvia.io/connect/token",
    ClientId = "client-id",
    ClientSecret = "secret"
});
var token = tokenResponse.AccessToken;

Etter (TokenClient - fungerer uten eksterne avhengigheter):

Med Dependency Injection:

// I Program.cs - kun én gang
builder.Services.AddElvidTokenProvider(options =>
{
    options.TokenEndpoint = builder.Configuration.EnsureHasValue("system:kv:elvid:tokenendpoint");
    options.ClientId = builder.Configuration.EnsureHasValue("system:kv:elvid:clientid");
    options.ClientSecret = builder.Configuration.EnsureHasValue("system:kv:elvid:clientsecret");
});

// Client credentials - caches automatisk
var token = await _tokenProvider.GetAccessTokenAsync([]);

// Password grant (for smoketests)
var userToken = await _tokenProvider.GetAccessTokenAsync("testuser", "testpass", []);

Uten Dependency Injection (smoketests):

// Direkte opprettelse - perfect for smoketests
var tokenProvider = ElvidTokenClientFactory.Create(
    "https://elvid.test-elvia.io/connect/token",
    "client-id",
    "client-secret");

var token = await tokenProvider.GetAccessTokenAsync("testuser", "testpass", []);

Fordeler

  • Løser IdentityModel-problem - Ingen avhengighet til IdentityModel eller Duende pakker
  • Client Credentials + Password Grant - Støtter både machine-to-machine og user authentication
  • Automatisk caching - Thread-safe med per-scope og per-user caching
  • Multiple named clients - Factory pattern for separate API konfigurasjoner (Convey, Kuma etc.)
  • HttpClient-integrasjon - Automatisk Bearer token påføring (også uten scopes)
  • Retry-logikk - Automatisk retry ved 5xx feil
  • Ingen scopes påkrevd - Client credentials flow uten scopes
  • Fjerner duplikat kode - Erstatter alle ElvidAccessTokenService kopier
  • Perfect for smoketests - Password grant støtte og standalone factory
  • Standalone support - ElvidTokenClientFactory.Create() for bruk uten DI

Publisering

Tag en versjon for å publisere til NuGet:

git tag tokenclient-v1.0.0
git push origin tokenclient-v1.0.0
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
2.3.0 13,513 1/8/2026
2.2.0 320 1/6/2026
2.1.0 3,121 12/1/2025
2.0.0 526 12/1/2025
1.6.0 4,895 10/28/2025
1.5.1 1,612 10/10/2025
1.5.0 731 10/8/2025
1.4.0 626 10/7/2025
1.3.0 1,909 9/30/2025
1.2.0 384 9/29/2025
1.1.0 329 9/26/2025
1.0.1 191 9/26/2025

v1.5.0:
- Added automatic domain detection and translation (.no vs .io) for ElvID token endpoints
- TokenClient now detects if application runs on elvia.no or elvia.io domain and adjusts token endpoint accordingly
- Similar to AtlasUrl logic, but domain-aware based on incoming HTTP requests
- Fixes issues where applications on .no domain tried to call ElvID on .io (and vice versa)
- Uses IHttpContextAccessor to detect current host domain
- Changed default Create() method to use TokenEndpoint (recommended approach)
- Added CreateWithAuthority() for backwards compatibility with Authority-based discovery
- Updated README to recommend TokenEndpoint as primary configuration method
- TokenEndpoint is simpler, faster, and more robust than Authority-based discovery
- Breaking change: Existing ElvidTokenClientFactory.Create(authority, ...) calls will now interpret first parameter as TokenEndpoint. Use CreateWithAuthority() for Authority.
- Fully backward compatible - works seamlessly for both single-domain and multi-domain deployments

v1.4.0:
- Added TokenEndpoint option to bypass discovery (CRITICAL FIX for internal ElvID service calls)
- Added AddElvidJwtAuthentication() extension method for standard JWT Bearer authentication setup
- Added AddElvidJwtBearer() for multiple authentication schemes support
- Fixes deployment issues when discovery endpoint is not accessible from internal services
- Simplifies common JWT authentication configuration across applications consuming ElvID tokens
- Fully backward compatible - existing code works unchanged

v1.3.0:
- Enhanced AddElvidAuthHandler to support named token providers
- Smart parameter detection: single string = provider name, multiple = scopes
- Enables proper HttpClient integration with multiple named providers
- Fixes integration with IElvidTokenProviderFactory

v1.2.0:
- Added SetBearerToken extension method for easier migration from IdentityModel
- Improved documentation for HttpClient usage patterns

v1.1.0:
- Added Password Grant support for smoketests and user authentication
- Added standalone factory (ElvidTokenClientFactory.Create) for non-DI scenarios
- Added multiple named client support via IElvidTokenProviderFactory
- Removed scope requirement from HttpClient extensions
- Thread-safe per-user token caching for Password Grant
- Enhanced error handling and logging

v1.0.x: Initial OAuth2 Client Credentials support