Tokenx Auth logo

Tokenx Auth

Organization
navikt
tokenx-auth

Tjeneste-til-tjeneste-autentisering med TokenX token exchange i Nais

Overview

Publishernavikt
Repositorycopilot
Skill nametokenx-auth
Stars
60
Forks
16
Bundled files
1
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • 1 bundled files

    Scripts, templates, and references the model can read while it works. Files are read-only and never executed.

  • Open source

    Published by navikt on GitHub. Read the source before you install it.

Installation

Install the Tokenx Auth AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/navikt/copilot/tree/main/skills/tokenx-auth
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

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
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Tokenx Auth in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Tokenx Auth on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Tokenx Auth is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

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

Bundled files

The model reads these on demand while the skill is loaded. They are exposed as readable files and are never executed.

Frequently asked questions

What does the Tokenx Auth AI skill do?

Tjeneste-til-tjeneste-autentisering med TokenX token exchange i Nais

Why use Tokenx Auth on TypingMind?

Because you install it once and use it with any model. Tokenx Auth is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Tokenx Auth in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/navikt/copilot/tree/main/skills/tokenx-auth. TypingMind reads its SKILL.md and bundles its files and installs it as a skill you can enable per chat.

Which AI models can use Tokenx Auth?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Tokenx Auth?

As many as you like. As long as a model supports skills, you can use Tokenx Auth with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Tokenx Auth AI skill free?

Yes. It is published on GitHub by navikt under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇