Elvia.Elvid.TokenClient
1.5.0
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
<PackageReference Include="Elvia.Elvid.TokenClient" Version="1.5.0" />
<PackageVersion Include="Elvia.Elvid.TokenClient" Version="1.5.0" />
<PackageReference Include="Elvia.Elvid.TokenClient" />
paket add Elvia.Elvid.TokenClient --version 1.5.0
#r "nuget: Elvia.Elvid.TokenClient, 1.5.0"
#:package Elvia.Elvid.TokenClient@1.5.0
#addin nuget:?package=Elvia.Elvid.TokenClient&version=1.5.0
#tool nuget:?package=Elvia.Elvid.TokenClient&version=1.5.0
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:
TokenEndpointer anbefalt overAuthority(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 | Versions 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. |
-
net8.0
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 8.0.0)
- Microsoft.AspNetCore.Http (>= 2.2.2)
- Microsoft.Extensions.Configuration.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Configuration.Binder (>= 8.0.0)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Http (>= 8.0.0)
- Microsoft.Extensions.Logging.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Options (>= 8.0.0)
- System.Text.Json (>= 8.0.5)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
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