소스 정보
- 저장소
- navikt/familie-tilbake-frontend
- 최근 소스 활동
- 2026년 4월 22일 07:10
- 감지된 SKILL.md 언어
- 영어
- 스타
- 1
- 포크
- 3
설치 방법
기본적으로 소스를 먼저 확인하는 Prompt가 선택됩니다. 직접 명령으로 전환하거나 로컬 사본을 다운로드할 수도 있습니다.
소스 파일 검토
설치 여부를 결정하기 전에 SKILL.md와 SkillsMP에 표시된 보조 파일을 읽어 보세요.
메뉴
기본적으로 소스를 먼저 확인하는 Prompt가 선택됩니다. 직접 명령으로 전환하거나 로컬 사본을 다운로드할 수도 있습니다.
설치 여부를 결정하기 전에 SKILL.md와 SkillsMP에 표시된 보조 파일을 읽어 보세요.
Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
직접 명령은 검토 Prompt를 거치지 않습니다. 실행하기 전에 소스를 확인하세요.
npx skills add https://github.com/navikt/familie-tilbake-frontend --skill tokenx-auth명령은 한 줄로 유지됩니다. 복사하기 전에 가로로 스크롤해 전체 내용을 확인하세요.
로컬 사본을 원하시나요? SkillsMP에서 현재 제공할 수 있는 파일을 다운로드하세요.
SOC 직업 분류 기준
SKILL.md 표시 중
| name | tokenx-auth |
| description | Service-to-service authentication using TokenX token exchange in Nais |
This skill provides patterns for secure service-to-service authentication using TokenX.
apiVersion: nais.io/v1alpha1
kind: Application
metadata:
name: my-app
spec:
tokenx:
enabled: true
accessPolicy:
outbound:
rules:
- application: user-service
namespace: team-user
This creates environment variables:
TOKEN_X_WELL_KNOWN_URLTOKEN_X_CLIENT_IDTOKEN_X_PRIVATE_JWKProduction pattern from navikt/tms-ktor-token-support - used across 198+ Nav repositories:
import com.github.benmanes.caffeine.cache.Cache
import com.github.benmanes.caffeine.cache.Caffeine
import com.nimbusds.jose.jwk.RSAKey
class CachingTokendingsService(
private val tokendingsConsumer: TokendingsConsumer,
private val jwtAudience: String,
private val clientId: String,
privateJwk: String,
maxCacheEntries: Long = 10000,
cacheExpiryMarginSeconds: Int = 10
) : TokendingsService {
private val cache: Cache<String, AccessTokenEntry> = Caffeine.newBuilder()
.maximumSize(maxCacheEntries)
.expireAfter(ExpiryPolicy(cacheExpiryMarginSeconds))
.build()
private val privateRsaKey = RSAKey.parse(privateJwk)
override suspend fun exchangeToken(token: String, targetApp: String): String {
val cacheKey = "$token:$targetApp".hashCode().toString()
return cache.get(cacheKey) {
performTokenExchange(token, targetApp)
}.accessToken
}
private suspend fun performTokenExchange(
token: String,
targetApp: String
): AccessTokenEntry {
val clientAssertion = createSignedAssertion(clientId, jwtAudience, privateRsaKey)
return tokendingsConsumer.exchangeToken(
subjectToken = token,
clientAssertion = clientAssertion,
targetApp = "cluster:namespace:$targetApp"
)
}
}
import com.nimbusds.jose.JWSAlgorithm
import com.nimbusds.jose.JWSHeader
import com.nimbusds.jose.crypto.RSASSASigner
import com.nimbusds.jose.jwk.RSAKey
import com.nimbusds.jwt.JWTClaimsSet
import com.nimbusds.jwt.SignedJWT
import java.time.Instant
import java.util.*
class TokenXClient(
private val tokenXUrl: String,
private val clientId: String,
private val privateJwk: String
) {
private val rsaKey = RSAKey.parse(privateJwk)
fun exchangeToken(
userToken: String,
targetApp: String,
targetNamespace: String = "default"
): String {
val audience = "cluster:$targetNamespace:$targetApp"
val clientAssertion = createClientAssertion()
val response = httpClient.post("$tokenXUrl/token") {
contentType(ContentType.Application.FormUrlEncoded)
setBody(
listOf(
"grant_type" to "urn:ietf:params:oauth:grant-type:token-exchange",
"client_assertion_type" to "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
"client_assertion" to clientAssertion,
"subject_token_type" to "urn:ietf:params:oauth:token-type:jwt",
to userToken,
to audience
).formUrlEncode()
)
}
tokenResponse = response.body<TokenResponse>()
tokenResponse.access_token
}
: String {
now = Instant.now()
claimsSet = JWTClaimsSet.Builder()
.subject(clientId)
.issuer(clientId)
.audience(tokenXUrl)
.issueTime(Date.from(now))
.expirationTime(Date.from(now.plusSeconds()))
.jwtID(UUID.randomUUID().toString())
.build()
signedJWT = SignedJWT(
JWSHeader.Builder(JWSAlgorithm.RS256)
.keyID(rsaKey.keyID)
.build(),
claimsSet
)
signedJWT.sign(RSASSASigner(rsaKey))
signedJWT.serialize()
}
}
(
access_token: String,
token_type: String,
expires_in:
)
import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.http.*
class UserServiceClient(
private val tokenXClient: TokenXClient,
private val httpClient: HttpClient,
private val userServiceUrl: String
) {
suspend fun getUser(userId: String, userToken: String): User {
val exchangedToken = tokenXClient.exchangeToken(
userToken = userToken,
targetApp = "user-service",
targetNamespace = "team-user"
)
val response = httpClient.get("$userServiceUrl/api/users/$userId") {
headers {
append(HttpHeaders.Authorization, "Bearer $exchangedToken")
}
}
return response.body<User>()
}
}
import com.auth0.jwk.JwkProviderBuilder
import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import java.net.URL
import java.security.interfaces.RSAPublicKey
class TokenValidator(
private val tokenXWellKnownUrl: String,
private val clientId: String
) {
private val metadata = fetchMetadata()
private val jwkProvider = JwkProviderBuilder(URL(metadata.jwks_uri)).build()
fun validate(token: String): Boolean {
return try {
val jwt = JWT.decode(token)
val jwk = jwkProvider.get(jwt.keyId)
val algorithm = Algorithm.RSA256(jwk.publicKey as RSAPublicKey, null)
val verifier = JWT.require(algorithm)
.withIssuer(metadata.issuer)
.withAudience(clientId)
.build()
verifier.verify(token)
true
} catch (e: Exception) {
logger.warn("Token validation failed", e)
false
}
}
private fun fetchMetadata(): OAuthMetadata {
return httpClient.get(tokenXWellKnownUrl).body()
}
}
data class OAuthMetadata(
issuer: String,
jwks_uri: String,
token_endpoint: String
)
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.auth.jwt.*
fun Application.configureTokenX() {
val tokenValidator = TokenValidator(
tokenXWellKnownUrl = environment.config.property("tokenx.well.known.url").getString(),
clientId = environment.config.property("tokenx.client.id").getString()
)
install(Authentication) {
jwt("tokenx") {
verifier(
JwkProviderBuilder(URL(tokenValidator.metadata.jwks_uri)).build(),
tokenValidator.metadata.issuer
) {
withAudience(tokenValidator.clientId)
}
validate { credential ->
if (credential.payload.audience.contains(tokenValidator.clientId)) {
JWTPrincipal(credential.payload)
} else {
null
}
}
}
}
routing {
authenticate("tokenx") {
get("/api/protected") {
val principal = call.principal<JWTPrincipal>()
val userId = principal?.payload?.subject
call.respond("Authenticated user: $userId")
}
}
}
}
fun main() {
val env = Environment.from(System.getenv())
val tokenXClient = TokenXClient(
tokenXUrl = env.tokenXUrl,
clientId = env.tokenXClientId,
privateJwk = env.tokenXPrivateJwk
)
val userServiceClient = UserServiceClient(
tokenXClient = tokenXClient,
httpClient = HttpClient(),
userServiceUrl = env.userServiceUrl
)
embeddedServer(Netty, port = 8080) {
configureTokenX()
routing {
authenticate("tokenx") {
get("/api/users/{id}") {
val userId = call.parameters["id"]!!
val userToken = call.request.headers["Authorization"]!!
.removePrefix("Bearer ")
val user = userServiceClient.getUser(userId, userToken)
call.respond(user)
}
}
}
}.start(wait = true)
}
import no.nav.security.mock.oauth2.MockOAuth2Server
import org.junit.jupiter.api.*
class TokenXTest {
private lateinit var mockOAuth2Server: MockOAuth2Server
@BeforeEach
fun setup() {
mockOAuth2Server = MockOAuth2Server()
mockOAuth2Server.start()
}
@AfterEach
fun teardown() {
mockOAuth2Server.shutdown()
}
@Test
fun `should exchange token successfully`() {
val userToken = mockOAuth2Server.issueToken(
issuerId = "tokenx",
subject = "user123",
audience = "my-app"
)
val tokenXClient = TokenXClient(
tokenXUrl = mockOAuth2Server.tokenEndpointUrl("tokenx").toString(),
clientId = "my-app",
privateJwk = generatePrivateJwk()
)
val exchangedToken = tokenXClient.exchangeToken(
userToken = userToken.serialize(),
targetApp = "user-service",
targetNamespace = "team-user"
)
assertNotNull(exchangedToken)
}
}