Logo di Tokenx Auth

Tokenx Auth

Organizzazione
navikt
tokenx-auth

Autenticazione da servizio a servizio con scambio di token TokenX in Nais

Add to TypingMind

Panoramica

Pubblicato danavikt
Repositorycopilot
Nome della skilltokenx-auth
Stelle
60
Fork
16
File inclusi
1
LicenzaMIT
Link
  • Istruzioni in Markdown

    Un file SKILL.md che il modello carica quando serve, consumando token solo quando una richiesta è effettivamente pertinente.

  • Funziona con qualsiasi LLM

    Le skill IA sono in semplice Markdown, non in codice specifico di un fornitore, quindi funzionano con GPT, Claude, Gemini, Grok o un modello locale.

  • File inclusi: 1

    Script, template e riferimenti che il modello può leggere mentre lavora. I file sono di sola lettura e non vengono mai eseguiti.

  • Open source

    Pubblicata da navikt su GitHub. Leggi i sorgenti prima di installarla.

Installazione

Installa la skill IA Tokenx Auth in TypingMind per usarla con qualsiasi LLM, oppure copiala in un altro agente in grado di leggere SKILL.md.

1

Installa in TypingMind

TypingMind installa una skill direttamente dalla sua cartella GitHub: legge SKILL.md, raccoglie i file delle risorse e salva il risultato in locale.

  1. Apri l'app e vai su Plugin → Skill.
  2. Scegli "Installa da GitHub".
  3. Incolla l'URL della cartella della skill riportato qui sotto e conferma.
    https://github.com/navikt/copilot/tree/main/skills/tokenx-auth
  4. Attiva la skill in ogni chat in cui vuoi averla a disposizione.
Plugin → Skill → Aggiungi skill → Da URL GitHub, poi incolla l'URL della cartella e premi Continua.
2

Installa in un altro agente

Qualsiasi agente che legge il formato Agent Skills può usare questa skill: copia la cartella della skill nella directory delle skill di quell'agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/navikt/copilot.git /tmp/copilot
mkdir -p .claude/skills
cp -r /tmp/copilot/skills/tokenx-auth .claude/skills/tokenx-auth
Dopo la copia, riavvia Claude Code per caricare la nuova skill.

Usala in TypingMind

Attiva Tokenx Auth in qualsiasi chat di TypingMind e al resto pensa il modello. Il nome e la descrizione della skill sono nel prompt di sistema e, non appena arriva una richiesta pertinente, il modello carica da solo le istruzioni complete: non devi mai richiamarla manualmente e non consuma token finché non viene effettivamente usata.

Il modello carica automaticamente Tokenx Auth non appena riceve una richiesta pertinente.

Funziona con qualsiasi modello IA

Le skill IA sono semplici istruzioni in Markdown, non codice specifico di un fornitore, quindi Tokenx Auth non è vincolata al modello per cui è stata scritta. Installala una sola volta in TypingMind e usala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modello locale che esegui tu, sempre con le tue chiavi API.

  • Caricata solo quando serve

    Il prompt di sistema contiene solo il nome e la descrizione. Le istruzioni vengono recuperate alla prima richiesta pertinente, quindi una skill inutilizzata non costa nulla.

  • Cambia modello durante la chat

    Poiché la skill è composta da istruzioni e non da codice, continua a funzionare anche se cambi modello: il nuovo modello legge lo stesso file SKILL.md.

Istruzioni della skill

Questo è il contenuto di SKILL.md che il modello carica. Leggilo prima dell'installazione: una skill è un insieme di istruzioni che il tuo modello seguirà.

TokenX Authentication Skill

This skill provides patterns for secure service-to-service authentication using TokenX. Token exchange and validation go through Texas, the Nais token sidecar. Do not sign client assertions or verify JWTs yourself.

The examples use Ktor 3 and need these artifacts besides Ktor server and client: ktor-client-content-negotiation, ktor-serialization-jackson, and for tests ktor-client-mock and kotlinx-coroutines-test.

Workflow

  1. Enable TokenX in the Nais manifest and define access policies
  2. Exchange tokens through Texas
  3. Call downstream services with the exchanged token
  4. Validate inbound TokenX tokens through Texas
  5. Integrate with Ktor authentication
  6. Test with a stubbed Texas

1. Nais Manifest Setup

yaml
apiVersion: nais.io/v1alpha1
kind: Application
metadata:
  name: my-app
spec:
  tokenx:
    enabled: true

  accessPolicy:
    outbound:
      rules:
        - application: user-service
          namespace: team-user

Nais injects these environment variables when tokenx.enabled is true:

  • NAIS_TOKEN_EXCHANGE_ENDPOINT
  • NAIS_TOKEN_INTROSPECTION_ENDPOINT

2. Token Exchange

POST to NAIS_TOKEN_EXCHANGE_ENDPOINT (docs). Texas signs the client assertion, caches tokens and never returns an expired one, so you need no cache or key handling of your own.

If the target rejects a token after its access policy changed, retry once with "skip_cache": true in the request body to get a fresh token.

kotlin
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.http.*

class TexasClient(
    private val httpClient: HttpClient,
    private val exchangeEndpoint: String = System.getenv("NAIS_TOKEN_EXCHANGE_ENDPOINT"),
    private val introspectionEndpoint: String = System.getenv("NAIS_TOKEN_INTROSPECTION_ENDPOINT"),
) {
    /** target: "<cluster>:<namespace>:<app>" */
    suspend fun exchange(userToken: String, target: String): String =
        httpClient.post(exchangeEndpoint) {
            contentType(ContentType.Application.Json)
            setBody(mapOf("identity_provider" to "tokenx", "target" to target, "user_token" to userToken))
        }.body<TokenResponse>().access_token

    suspend fun introspect(token: String): Map<String, Any?> =
        httpClient.post(introspectionEndpoint) {
            contentType(ContentType.Application.Json)
            setBody(mapOf("identity_provider" to "tokenx", "token" to token))
        }.body()
}

data class TokenResponse(val access_token: String, val expires_in: Int, val token_type: String)

Create the HttpClient with expectSuccess = true and ContentNegotiation with Jackson. Texas answers errors with 400 or 500 and a body with error and error_description, and expectSuccess turns those into exceptions instead of a half-parsed response.

3. Calling Another Service

kotlin
class UserServiceClient(
    private val texas: TexasClient,
    private val httpClient: HttpClient,
    private val userServiceUrl: String
) {
    suspend fun getUser(userId: String, userToken: String): User {
        // NAIS_CLUSTER_NAME is injected by Nais, e.g. "dev-gcp" or "prod-gcp"
        val target = "${System.getenv("NAIS_CLUSTER_NAME")}:team-user:user-service"
        val exchangedToken = texas.exchange(userToken, target)

        return httpClient.get("$userServiceUrl/api/users/$userId") {
            bearerAuth(exchangedToken)
        }.body()
    }
}

4. Validating Inbound Tokens

POST the token to NAIS_TOKEN_INTROSPECTION_ENDPOINT (docs). The response is always HTTP 200: active: true with the token's claims, or active: false with an error.

Texas checks the signature, iss, aud (your TokenX client id), exp, iat and nbf. Your app must still check:

  • acr, if you require a security level. Both Level4 and idporten-loa-high occur.
  • client_id, if you authorize per calling app.
  • pid, against the resource the user asks for.

If Texas itself fails (network error, 5xx), let the request fail with 5xx. Do not treat it as 401: that hides an outage.

If you would rather use a library, use token-validation-ktor from navikt/token-support. Never verify JWTs by hand.

5. Ktor Integration

kotlin
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.response.*
import io.ktor.server.routing.*

// Ktor 3: a principal no longer needs to implement Principal
data class TokenXPrincipal(val token: String, val claims: Map<String, Any?>)

fun Application.configureTokenX(texas: TexasClient) {
    install(Authentication) {
        bearer("tokenx") {
            authenticate { credential ->
                // Exceptions from Texas propagate and give 5xx, not 401
                val result = texas.introspect(credential.token)
                if (result["active"] == true) TokenXPrincipal(credential.token, result) else null
            }
        }
    }

    routing {
        authenticate("tokenx") {
            get("/api/protected") {
                val principal = call.principal<TokenXPrincipal>()!!
                call.respond("Authenticated user: ${principal.claims["pid"]}")
            }
        }
    }
}

Complete Example

kotlin
fun main() {
    val httpClient = HttpClient {
        expectSuccess = true
        install(ContentNegotiation) { jackson() }
    }
    val texas = TexasClient(httpClient)
    val userServiceClient = UserServiceClient(texas, httpClient, System.getenv("USER_SERVICE_URL"))

    embeddedServer(Netty, port = 8080) {
        configureTokenX(texas)

        routing {
            authenticate("tokenx") {
                get("/api/users/{id}") {
                    val principal = call.principal<TokenXPrincipal>()!!
                    call.respond(userServiceClient.getUser(call.parameters["id"]!!, principal.token))
                }
            }
        }
    }.start(wait = true)
}

Testing

Texas is not part of your local setup, so stub it with Ktor's MockEngine:

kotlin
import io.ktor.client.engine.mock.*
import io.ktor.server.testing.*

private fun texasStub(body: String): TexasClient {
    val engine = MockEngine {
        respond(body, headers = headersOf(HttpHeaders.ContentType, "application/json"))
    }
    val client = HttpClient(engine) {
        expectSuccess = true
        install(ContentNegotiation) { jackson() }
    }
    return TexasClient(client, "http://texas/exchange", "http://texas/introspect")
}

@Test
fun `exchanges token through Texas`() = runTest {
    val texas = texasStub("""{"access_token":"exchanged","expires_in":3599,"token_type":"Bearer"}""")

    assertEquals("exchanged", texas.exchange("user-token", "dev-gcp:team-user:user-service"))
}

@Test
fun `rejects inactive token with 401`() = testApplication {
    val texas = texasStub("""{"active":false,"error":"token is expired"}""")
    application { configureTokenX(texas) }

    val response = client.get("/api/protected") { bearerAuth("expired-token") }

    assertEquals(HttpStatusCode.Unauthorized, response.status)
}

For tests that need real signed JWTs, navikt/mock-oauth2-server issues them.

Security Checklist

  • TokenX enabled in Nais manifest
  • Access policy defined for outbound calls
  • Inbound tokens validated through Texas (or token-support) on all protected endpoints
  • App checks acr, client_id and pid where it relies on them
  • Texas outages give 5xx, not 401
  • No hand-written JWT validation or client assertions
  • Tokens not logged or exposed
  • HTTPS enforced for all calls

File inclusi

Il modello legge questi file quando servono, mentre la skill è caricata. Sono accessibili in sola lettura e non vengono mai eseguiti.

Domande frequenti

Cosa fa la skill IA Tokenx Auth?

Autenticazione da servizio a servizio con scambio di token TokenX in Nais

Perché usare Tokenx Auth su TypingMind?

Perché la installi una volta e la usi con qualsiasi modello. Tokenx Auth è scritta in semplice Markdown anziché in codice specifico di un fornitore, quindi la stessa skill funziona con GPT-5, Claude, Gemini, Grok o un modello locale, e puoi cambiare modello durante la chat senza che la skill smetta di funzionare. TypingMind usa le tue chiavi API, quindi paghi direttamente i fornitori anziché un abbonamento per posto utente, e le tue skill e chat restano nel tuo spazio di archiviazione.

Come installo Tokenx Auth in TypingMind?

Apri Plugin → Skill → Installa da GitHub in TypingMind e incolla https://github.com/navikt/copilot/tree/main/skills/tokenx-auth. TypingMind legge il file SKILL.md, include i file associati e installa la skill, che puoi abilitare per ogni singola chat.

Quali modelli IA possono usare Tokenx Auth?

Qualsiasi modello che colleghi a TypingMind. Le skill IA sono semplici istruzioni in Markdown anziché codice specifico di un fornitore, quindi GPT, Claude, Gemini, Grok e i modelli locali possono tutti caricare questa skill quando una richiesta corrisponde al suo scopo.

Quanti modelli IA posso usare con Tokenx Auth?

Quanti ne vuoi. Se un modello supporta le skill, puoi usarlo con Tokenx Auth: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e molti altri, tutti su TypingMind con le tue chiavi API.

La skill IA Tokenx Auth è gratuita?

Sì. È pubblicata su GitHub da navikt con licenza MIT. Paghi solo il tuo fornitore IA per i token che usi.

Cosa sono le skill IA?

Una skill IA è un pacchetto di istruzioni riutilizzabili che insegna a un modello IA come svolgere un'attività specifica. Segue il formato aperto Agent Skills: un file SKILL.md con un nome e una descrizione, più eventuali script, template o file di riferimento di cui il modello potrebbe aver bisogno. Il modello legge le istruzioni solo quando la tua richiesta corrisponde alla skill, quindi una skill installata non comporta costi finché non viene usata.

In cosa si differenziano le skill IA dai plugin o dai server MCP?

Un plugin o un server MCP fornisce a un modello nuovi strumenti da richiamare: codice che viene eseguito da qualche parte e restituisce un risultato. Una skill IA, invece, fornisce al modello conoscenze e procedure: come affrontare un'attività, quali passaggi seguire e quali caratteristiche deve avere un buon output. Le skill sono semplici istruzioni in Markdown, quindi non richiedono server, chiavi API né ambienti di esecuzione e funzionano con qualsiasi modello.

Elenco completo

Crea subito il tuo spazio di lavoro AI

Iscriviti alla nostra newsletter per ricevere aggiornamenti sulle nuove funzionalità e sulle prossime iniziative a premi 👇