Tokenx Authのロゴ

Tokenx Auth

組織
navikt
tokenx-auth

NaisでのTokenXトークン交換によるサービス間認証

Add to TypingMind

概要

公開者navikt
リポジトリcopilot
スキル名tokenx-auth
スター
60
フォーク
16
同梱ファイル
1
ライセンスMIT
リンク
  • Markdown形式の指示

    モデルが必要に応じて読み込むSKILL.mdファイルです。関連するリクエストがあったときだけトークンを消費します。

  • どのLLMでも利用可能

    AIスキルはプロバイダー固有のコードではなく、通常のMarkdownなので、GPT、Claude、Gemini、Grok、ローカルモデルで利用できます。

  • 1個の同梱ファイル

    モデルが作業中に読み取れるスクリプト、テンプレート、参考資料です。ファイルは読み取り専用で、実行されることはありません。

  • オープンソース

    naviktがGitHubで公開しています。インストールする前にソースを確認してください。

インストール

AIスキル「Tokenx Auth」をTypingMindにインストールすれば、どのLLMでも利用できます。SKILL.mdを読み取れる別のAIエージェントに追加することもできます。

1

TypingMindにインストール

TypingMindはGitHubフォルダから直接スキルをインストールします。SKILL.mdを読み取り、リソースファイルをまとめてローカルに保存します。

  1. アプリを開き、「プラグイン」→「スキル」に移動します。
  2. 「GitHubからインストール」を選択します。
  3. 以下のスキルフォルダのURLを貼り付けて確定します。
    https://github.com/navikt/copilot/tree/main/skills/tokenx-auth
  4. スキルを利用したいチャットごとに、そのスキルを有効にしてください。
「プラグイン」→「スキル」→「スキルを追加」→「GitHubのURLから」を選択し、フォルダのURLを貼り付けて「続行」を押します。
2

別のAIエージェントにインストール

Agent Skills形式を読み取れるAIエージェントなら、このスキルを利用できます。フォルダをそのAIエージェントのスキルディレクトリにコピーしてください。

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
コピー後、新しいスキルを読み込むためにClaude Codeを再起動してください。

TypingMindで使用

TypingMindのチャットでTokenx Authを有効にするだけで、あとはモデルが対応します。名前と説明がシステムプロンプトに含まれ、関連するリクエストがあると、モデルが指示の全文を自動で読み込みます。手動で呼び出す必要はなく、実際に使用されるまでトークンを消費しません。

関連するリクエストがあるとすぐに、モデルが自動的にTokenx Authを読み込みます。

どのAIモデルでも利用可能

AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、Tokenx Authは作成時に想定されたモデルに縛られません。TypingMindに一度インストールすれば、ご自身のAPIキーを使って、GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama、またはご自身で実行するローカルモデルで利用できます。

  • 必要なときだけ読み込み

    システムプロンプトには名前と説明だけが含まれます。関連するリクエストが初めてあったときに指示を取得するため、スキルを使わない間は指示の読み込みにトークンを消費しません。

  • チャットの途中でモデルを切り替え

    スキルはコードではなく指示なので、モデルを切り替えてもそのまま使えます。次のモデルも同じSKILL.mdを読み込みます。

スキルの指示

モデルが読み込むSKILL.mdの内容です。スキルはモデルが従う指示なので、インストールする前に確認してください。

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

同梱ファイル

スキルが読み込まれている間、モデルは必要に応じてこれらを読み取ります。読み取り可能なファイルとして提供され、実行されることはありません。

よくある質問

AIスキル「Tokenx Auth」では何ができますか?

NaisでのTokenXトークン交換によるサービス間認証

TypingMindでTokenx Authを使うメリットは何ですか?

一度インストールすれば、どのモデルでも使えるからです。Tokenx Authはプロバイダー固有のコードではなく、通常のMarkdownで記述されているため、同じスキルをGPT-5、Claude、Gemini、Grok、ローカルモデルで利用できます。チャットの途中でモデルを切り替えても、そのまま使い続けられます。TypingMindは自分のAPIキーで動作するため、シート単位のサブスクリプションではなく、プロバイダーに直接料金を支払います。スキルとチャットは自分のストレージに保持されます。

TypingMindにTokenx Authをインストールするにはどうすればよいですか?

TypingMindで「プラグイン」→「スキル」→「GitHubからインストール」を開き、https://github.com/navikt/copilot/tree/main/skills/tokenx-authを貼り付けてください。TypingMindがSKILL.mdを読み込み、関連ファイルをまとめて、チャットごとに有効にできるスキルとしてインストールします。

Tokenx Authを使えるAIモデルはどれですか?

TypingMindに接続したどのモデルでも利用できます。AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、GPT、Claude、Gemini、Grok、ローカルモデルのいずれも、リクエストの内容がこのスキルの用途に合ったときに、このスキルを読み込めます。

Tokenx Authで使えるAIモデルの数に制限はありますか?

数に制限はありません。スキルに対応したモデルであれば、GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llamaなど、どのモデルでもTokenx Authを利用できます。すべてTypingMind上で、自分のAPIキーを使って利用できます。

AIスキル「Tokenx Auth」は無料ですか?

はい。naviktがMITライセンスのもとでGitHubに公開しています。ご利用のAIプロバイダーに支払うのは、使用したトークンの料金だけです。

AIスキルとは何ですか?

AIスキルは、特定のタスクの実行方法をAIモデルに教える、再利用可能な指示のセットです。オープンなAgent Skills形式に従い、名前と説明を含むSKILL.mdファイルに加え、モデルが必要とするスクリプト、テンプレート、参照ファイルで構成されます。モデルはリクエストがスキルに合致したときだけ指示を読み込むため、インストール済みのスキルも、使うまでは費用がかかりません。

AIスキルは、プラグインやMCPサーバーとどう違いますか?

プラグインやMCPサーバーは、モデルが呼び出せる新しいツールを提供します。ツールとは、どこかで実行され、結果を返すコードです。一方、AIスキルは、タスクへの取り組み方、従うべき手順、望ましい出力の例といった知識や進め方をモデルに伝えます。スキルは通常のMarkdownで記述されているため、サーバー、APIキー、実行環境は不要で、どのモデルでも利用できます。

すべて見る

今すぐ自分専用のAIワークスペースを作成

ニュースレターに登録すると、新機能や今後のプレゼント企画のお知らせが届きます👇