From 39e1e51d03e1bbeee938f92e4e3d5b521b93ce4f Mon Sep 17 00:00:00 2001 From: Jan-Olav Eide Date: Mon, 15 Jan 2024 14:16:45 +0100 Subject: [PATCH] chore --- .../support/client/core/ClientProperties.kt | 2 +- .../support/client/core/OAuth2GrantType.kt | 19 ----------- .../client/core/auth/ClientAssertion.kt | 4 --- .../client/core/http/OAuth2HttpClient.kt | 2 +- .../client/core/http/OAuth2HttpHeaders.kt | 4 +-- .../client/core/http/OAuth2HttpRequest.kt | 3 +- .../core/oauth2/AbstractOAuth2TokenClient.kt | 33 +++++++++---------- .../core/oauth2/OAuth2AccessTokenService.kt | 11 +++---- .../core/http/SimpleOAuth2HttpClient.kt | 11 ++++--- .../core/oauth2/OnBehalfOfTokenClientTest.kt | 9 +++-- .../token/support/ktor/oauth/ClientConfig.kt | 5 ++- .../ClientConfigurationPropertiesMatcher.kt | 2 +- .../spring/oauth2/DefaultOAuth2HttpClient.kt | 22 ++++++------- .../oauth2/OAuth2ClientRequestInterceptor.kt | 2 +- .../core/configuration/IssuerConfiguration.kt | 9 ++--- .../core/configuration/IssuerProperties.kt | 2 +- .../support/filter/JwtTokenExpiryFilter.kt | 20 +++++------ 17 files changed, 62 insertions(+), 98 deletions(-) delete mode 100644 token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/OAuth2GrantType.kt diff --git a/token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/ClientProperties.kt b/token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/ClientProperties.kt index 26304685..cae41441 100644 --- a/token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/ClientProperties.kt +++ b/token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/ClientProperties.kt @@ -41,7 +41,7 @@ class ClientProperties @JvmOverloads constructor(var tokenEndpointUrl: URI? = nu private fun endpointUrlFromMetadata(wellKnown: URI?) = runCatching { - wellKnown?.let { AuthorizationServerMetadata.parse(DefaultResourceRetriever().retrieveResource(wellKnown.toURL()).content).tokenEndpointURI } + wellKnown?.let { AuthorizationServerMetadata.parse(DefaultResourceRetriever().retrieveResource(it.toURL()).content).tokenEndpointURI } ?: throw OAuth2ClientException("Well-known url cannot be null, please check your configuration") }.getOrElse { when(it) { diff --git a/token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/OAuth2GrantType.kt b/token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/OAuth2GrantType.kt deleted file mode 100644 index baedec3b..00000000 --- a/token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/OAuth2GrantType.kt +++ /dev/null @@ -1,19 +0,0 @@ -package no.nav.security.token.support.client.core - -import com.nimbusds.oauth2.sdk.GrantType -import kotlin.DeprecationLevel.WARNING - -@Deprecated("Use GrantType from nimbus instead", ReplaceWith("GrantType"), WARNING) -data class OAuth2GrantType(val value : String) { - companion object { - @JvmField - @Deprecated("Use com.nimbusds.oauth2.sdk.GrantType instead", ReplaceWith("GrantType.JWT_BEARER"), WARNING) - val JWT_BEARER = GrantType(GrantType.JWT_BEARER.value) - @JvmField - @Deprecated("Use com.nimbusds.oauth2.sdk.GrantType instead", ReplaceWith("GrantType.CLIENT_CREDENTIALS"), WARNING) - val CLIENT_CREDENTIALS = GrantType(GrantType.CLIENT_CREDENTIALS.value) - @JvmField - @Deprecated("Use com.nimbusds.oauth2.sdk.GrantType instead", ReplaceWith("GrantType.TOKEN_EXCHANGE"), WARNING) - val TOKEN_EXCHANGE = GrantType(GrantType.TOKEN_EXCHANGE.value) - } -} \ No newline at end of file diff --git a/token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/auth/ClientAssertion.kt b/token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/auth/ClientAssertion.kt index b0dd6f31..7df6103f 100644 --- a/token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/auth/ClientAssertion.kt +++ b/token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/auth/ClientAssertion.kt @@ -32,10 +32,6 @@ class ClientAssertion(private val tokenEndpointUrl : URI, private val clientId : .issueTime(Date.from(this)) .build()).serialize() } - - @Deprecated("Use com.nimbusds.oauth2.sdk.auth.JWTAuthentication instead", ReplaceWith("JWTAuthentication.CLIENT_ASSERTION_TYPE"), WARNING) - fun assertionType() = CLIENT_ASSERTION_TYPE - private fun createSignedJWT(rsaJwk : RSAKey, claimsSet : JWTClaimsSet) = runCatching { SignedJWT(JWSHeader.Builder(RS256) diff --git a/token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/http/OAuth2HttpClient.kt b/token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/http/OAuth2HttpClient.kt index c3acfbb5..b7a5ed67 100644 --- a/token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/http/OAuth2HttpClient.kt +++ b/token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/http/OAuth2HttpClient.kt @@ -3,5 +3,5 @@ package no.nav.security.token.support.client.core.http import no.nav.security.token.support.client.core.oauth2.OAuth2AccessTokenResponse interface OAuth2HttpClient { - fun post(request : OAuth2HttpRequest) : OAuth2AccessTokenResponse? + fun post(request : OAuth2HttpRequest) : OAuth2AccessTokenResponse } \ No newline at end of file diff --git a/token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/http/OAuth2HttpHeaders.kt b/token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/http/OAuth2HttpHeaders.kt index 32904366..086049ea 100644 --- a/token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/http/OAuth2HttpHeaders.kt +++ b/token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/http/OAuth2HttpHeaders.kt @@ -4,7 +4,7 @@ import java.lang.String.CASE_INSENSITIVE_ORDER import java.util.Objects import java.util.TreeMap -class OAuth2HttpHeaders (val headers : Map>) { +class OAuth2HttpHeaders(val headers : Map> = emptyMap()) { override fun equals(other : Any?) : Boolean { if (this === other) return true @@ -27,7 +27,7 @@ class OAuth2HttpHeaders (val headers : Map>) { companion object { @JvmField - val NONE = OAuth2HttpHeaders(emptyMap()) + val NONE = OAuth2HttpHeaders() @JvmStatic fun of(headers : Map>) = OAuth2HttpHeaders(headers) diff --git a/token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/http/OAuth2HttpRequest.kt b/token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/http/OAuth2HttpRequest.kt index bd6a8b64..0d3f66ff 100644 --- a/token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/http/OAuth2HttpRequest.kt +++ b/token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/http/OAuth2HttpRequest.kt @@ -1,7 +1,6 @@ package no.nav.security.token.support.client.core.http import java.net.URI -import java.util.Collections.unmodifiableMap import no.nav.security.token.support.client.core.http.OAuth2HttpHeaders.Companion.NONE class OAuth2HttpRequest(val tokenEndpointUrl : URI, val oAuth2HttpHeaders : OAuth2HttpHeaders = NONE, val formParameters : Map) { @@ -18,7 +17,7 @@ class OAuth2HttpRequest(val tokenEndpointUrl : URI, val oAuth2HttpHeaders : OAut fun formParameters(entries: Map) = this.also { formParameters.putAll(entries) } - fun build(): OAuth2HttpRequest = OAuth2HttpRequest(tokenEndpointUrl, oAuth2HttpHeaders, unmodifiableMap(formParameters)) + fun build(): OAuth2HttpRequest = OAuth2HttpRequest(tokenEndpointUrl, oAuth2HttpHeaders, formParameters.toMap()) @Override override fun toString() = "OAuth2HttpRequest.OAuth2HttpRequestBuilder(tokenEndpointUrl=$tokenEndpointUrl, oAuth2HttpHeaders=$oAuth2HttpHeaders, entries=$formParameters" diff --git a/token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/oauth2/AbstractOAuth2TokenClient.kt b/token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/oauth2/AbstractOAuth2TokenClient.kt index 94535b7b..d8847dca 100644 --- a/token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/oauth2/AbstractOAuth2TokenClient.kt +++ b/token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/oauth2/AbstractOAuth2TokenClient.kt @@ -10,6 +10,7 @@ import com.nimbusds.oauth2.sdk.auth.JWTAuthentication import java.lang.String.join import java.nio.charset.StandardCharsets.UTF_8 import java.util.Base64.getEncoder +import org.checkerframework.checker.nullness.qual.NonNull import no.nav.security.token.support.client.core.ClientProperties import no.nav.security.token.support.client.core.OAuth2ClientException import no.nav.security.token.support.client.core.OAuth2ParameterNames.CLIENT_ASSERTION @@ -23,12 +24,12 @@ import no.nav.security.token.support.client.core.http.OAuth2HttpClient import no.nav.security.token.support.client.core.http.OAuth2HttpHeaders import no.nav.security.token.support.client.core.http.OAuth2HttpRequest -abstract class AbstractOAuth2TokenClient internal constructor(private val oAuth2HttpClient : OAuth2HttpClient) { +abstract class AbstractOAuth2TokenClient internal constructor(private val oAuth2HttpClient : OAuth2HttpClient) { protected abstract fun formParameters(grantRequest : T) : Map fun getTokenResponse(grantRequest : T) = - grantRequest?.clientProperties?.let { + grantRequest.clientProperties.let { runCatching { oAuth2HttpClient.post(OAuth2HttpRequest.builder(it.tokenEndpointUrl!!) .oAuth2HttpHeaders(OAuth2HttpHeaders.of(tokenRequestHeaders(it))) @@ -57,7 +58,7 @@ abstract class AbstractOAuth2TokenClient intern } private fun defaultFormParameters(grantRequest : T) = - grantRequest?.clientProperties?.let { + grantRequest.clientProperties.let { defaultClientAuthenticationFormParameters(grantRequest).apply { put(GRANT_TYPE,grantRequest.grantType.value) if (TOKEN_EXCHANGE != it.grantType) { @@ -67,22 +68,20 @@ abstract class AbstractOAuth2TokenClient intern } ?: throw OAuth2ClientException("ClientProperties cannot be null") private fun defaultClientAuthenticationFormParameters(grantRequest : T) = - grantRequest?.clientProperties?.let { - with(it) { - when (authentication.clientAuthMethod) { - CLIENT_SECRET_POST -> LinkedHashMap().apply { - put(CLIENT_ID, authentication.clientId) - put(CLIENT_SECRET, authentication.clientSecret!!) - } - PRIVATE_KEY_JWT -> LinkedHashMap().apply { - put(CLIENT_ID, authentication.clientId) - put(CLIENT_ASSERTION_TYPE, JWTAuthentication.CLIENT_ASSERTION_TYPE) - put(CLIENT_ASSERTION, ClientAssertion(tokenEndpointUrl!!, authentication).assertion()) - } - else -> mutableMapOf() + with(grantRequest.clientProperties) { + when (authentication.clientAuthMethod) { + CLIENT_SECRET_POST -> LinkedHashMap().apply { + put(CLIENT_ID, authentication.clientId) + put(CLIENT_SECRET, authentication.clientSecret!!) } + PRIVATE_KEY_JWT -> LinkedHashMap().apply { + put(CLIENT_ID, authentication.clientId) + put(CLIENT_ASSERTION_TYPE, JWTAuthentication.CLIENT_ASSERTION_TYPE) + put(CLIENT_ASSERTION, ClientAssertion(tokenEndpointUrl!!, authentication).assertion()) + } + else -> mutableMapOf() } - } ?: throw OAuth2ClientException("ClientProperties cannot be null") + } private fun basicAuth(username : String, password : String) = UTF_8.newEncoder().run { diff --git a/token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/oauth2/OAuth2AccessTokenService.kt b/token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/oauth2/OAuth2AccessTokenService.kt index b8cf3344..3b802124 100644 --- a/token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/oauth2/OAuth2AccessTokenService.kt +++ b/token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/oauth2/OAuth2AccessTokenService.kt @@ -20,7 +20,7 @@ class OAuth2AccessTokenService @JvmOverloads constructor(private val tokenResolv - fun getAccessToken(clientProperties : ClientProperties) : OAuth2AccessTokenResponse? { + fun getAccessToken(clientProperties : ClientProperties) : OAuth2AccessTokenResponse { log.trace("Getting access_token for grant={}", clientProperties.grantType) return when (clientProperties.grantType) { JWT_BEARER -> executeOnBehalfOf(clientProperties) @@ -40,18 +40,17 @@ class OAuth2AccessTokenService @JvmOverloads constructor(private val tokenResolv getFromCacheIfEnabled(ClientCredentialsGrantRequest(clientProperties), clientCredentialsGrantCache, clientCredentialsTokenClient::getTokenResponse) private fun tokenExchangeGrantRequest(clientProperties : ClientProperties) = - TokenExchangeGrantRequest(clientProperties, tokenResolver.token() ?: throw OAuth2ClientException("no authenticated jwt token found in validation context, cannot do token exchange")) + TokenExchangeGrantRequest(clientProperties, tokenResolver.token() ?: throw OAuth2ClientException("No authenticated jwt token found in validation context, cannot do token exchange")) private fun onBehalfOfGrantRequest(clientProperties : ClientProperties) = - OnBehalfOfGrantRequest(clientProperties, tokenResolver.token() ?: throw OAuth2ClientException("no authenticated jwt token found in validation context, cannot do on-behalf-of")) + OnBehalfOfGrantRequest(clientProperties, tokenResolver.token() ?: throw OAuth2ClientException("No authenticated jwt token found in validation context, cannot do on-behalf-of")) override fun toString() = "${javaClass.getSimpleName()} [clientCredentialsGrantCache=$clientCredentialsGrantCache, onBehalfOfGrantCache=$onBehalfOfGrantCache, tokenExchangeClient=$tokenExchangeClient, tokenResolver=$tokenResolver, onBehalfOfTokenClient=$onBehalfOfTokenClient, clientCredentialsTokenClient=$clientCredentialsTokenClient, exchangeGrantCache=$exchangeGrantCache]" companion object { - private val SUPPORTED_GRANT_TYPES = listOf(JWT_BEARER, CLIENT_CREDENTIALS, TOKEN_EXCHANGE - ) + private val SUPPORTED_GRANT_TYPES = listOf(JWT_BEARER, CLIENT_CREDENTIALS, TOKEN_EXCHANGE) private val log = LoggerFactory.getLogger(OAuth2AccessTokenService::class.java) - private fun getFromCacheIfEnabled(grantRequest : T, cache : Cache?, client : Function) = + private fun getFromCacheIfEnabled(grantRequest : T, cache : Cache?, client : Function) = cache?.let { log.debug("Cache is enabled so attempt to get from cache or update cache if not present.") cache[grantRequest, client] diff --git a/token-client-core/src/test/kotlin/no/nav/security/token/support/client/core/http/SimpleOAuth2HttpClient.kt b/token-client-core/src/test/kotlin/no/nav/security/token/support/client/core/http/SimpleOAuth2HttpClient.kt index 2fca326a..c884b3f0 100644 --- a/token-client-core/src/test/kotlin/no/nav/security/token/support/client/core/http/SimpleOAuth2HttpClient.kt +++ b/token-client-core/src/test/kotlin/no/nav/security/token/support/client/core/http/SimpleOAuth2HttpClient.kt @@ -31,11 +31,14 @@ class SimpleOAuth2HttpClient : OAuth2HttpClient { private fun HttpRequest.sendRequest() = newHttpClient().send(this, BodyHandlers.ofString()) private fun HttpResponse.processResponse() = - if (this.statusCode() in 200..299) { - MAPPER.readValue(body()) - } else { - throw OAuth2ClientException("Error response from token endpoint: ${this.statusCode()} ${this.body()}") + with(this) { + if (statusCode() in 200..299) { + MAPPER.readValue(body()) + } else { + throw OAuth2ClientException("Error response from token endpoint: ${statusCode()} ${body()}") + } } + private fun Map.toUrlEncodedString() = entries.joinToString("&") { (key, value) -> "$key=${URLEncoder.encode(value, UTF_8)}" } companion object { private val MAPPER = jacksonObjectMapper().configure(FAIL_ON_UNKNOWN_PROPERTIES, false) diff --git a/token-client-core/src/test/kotlin/no/nav/security/token/support/client/core/oauth2/OnBehalfOfTokenClientTest.kt b/token-client-core/src/test/kotlin/no/nav/security/token/support/client/core/oauth2/OnBehalfOfTokenClientTest.kt index 5fbe722b..99c1c685 100644 --- a/token-client-core/src/test/kotlin/no/nav/security/token/support/client/core/oauth2/OnBehalfOfTokenClientTest.kt +++ b/token-client-core/src/test/kotlin/no/nav/security/token/support/client/core/oauth2/OnBehalfOfTokenClientTest.kt @@ -51,9 +51,9 @@ internal class OnBehalfOfTokenClientTest { .contains("requested_token_use=on_behalf_of") .contains("assertion=$assertion") assertThat(response).isNotNull() - assertThat(response?.accessToken).isNotBlank() - assertThat(response?.expiresAt).isPositive() - assertThat(response?.expiresIn).isPositive() + assertThat(response.accessToken).isNotBlank() + assertThat(response.expiresAt).isPositive() + assertThat(response.expiresIn).isPositive() } @Test @@ -63,8 +63,7 @@ internal class OnBehalfOfTokenClientTest { val clientProperties = clientProperties(tokenEndpointUrl, JWT_BEARER) val oAuth2OnBehalfOfGrantRequest = OnBehalfOfGrantRequest(clientProperties, assertion) assertThrows { - val res = onBehalfOfTokenResponseClient.getTokenResponse(oAuth2OnBehalfOfGrantRequest) - println(res) + onBehalfOfTokenResponseClient.getTokenResponse(oAuth2OnBehalfOfGrantRequest) } } diff --git a/token-client-kotlin-demo/src/main/kotlin/no/nav/security/token/support/ktor/oauth/ClientConfig.kt b/token-client-kotlin-demo/src/main/kotlin/no/nav/security/token/support/ktor/oauth/ClientConfig.kt index c1db4ae1..db852df6 100644 --- a/token-client-kotlin-demo/src/main/kotlin/no/nav/security/token/support/ktor/oauth/ClientConfig.kt +++ b/token-client-kotlin-demo/src/main/kotlin/no/nav/security/token/support/ktor/oauth/ClientConfig.kt @@ -14,17 +14,16 @@ class ClientConfig(applicationConfig: ApplicationConfig, httpClient: HttpClient) internal val clients = applicationConfig.configList(CLIENTS_PATH) .associate { - val wellKnownUrl = it.propertyToString("well_known_url") val clientAuth = ClientAuthenticationProperties( it.propertyToString("authentication.client_id"), ClientAuthenticationMethod(it.propertyToString("authentication.client_auth_method")), it.propertyToStringOrNull("client_secret"), it.propertyToStringOrNull("authentication.client_jwk")) - it.propertyToString(CLIENT_NAME) to OAuth2Client(httpClient, wellKnownUrl, clientAuth, cacheConfig) + it.propertyToString(CLIENT_NAME) to OAuth2Client(httpClient, it.propertyToString("well_known_url"), clientAuth, cacheConfig) } companion object CommonConfigurationAttributes { - const val COMMON_PREFIX = "no.nav.security.jwt.client.registration" + private const val COMMON_PREFIX = "no.nav.security.jwt.client.registration" const val CLIENTS_PATH = "${COMMON_PREFIX}.clients" const val CACHE_PATH = "${COMMON_PREFIX}.cache" const val CLIENT_NAME = "client_name" diff --git a/token-client-spring/src/main/kotlin/no/nav/security/token/support/client/spring/oauth2/ClientConfigurationPropertiesMatcher.kt b/token-client-spring/src/main/kotlin/no/nav/security/token/support/client/spring/oauth2/ClientConfigurationPropertiesMatcher.kt index 3d45c05f..2baf1c57 100644 --- a/token-client-spring/src/main/kotlin/no/nav/security/token/support/client/spring/oauth2/ClientConfigurationPropertiesMatcher.kt +++ b/token-client-spring/src/main/kotlin/no/nav/security/token/support/client/spring/oauth2/ClientConfigurationPropertiesMatcher.kt @@ -9,7 +9,7 @@ import no.nav.security.token.support.client.spring.ClientConfigurationProperties * Default implementation that matcher host in request URL with the registration * name. Override for other strategies. Will typically be used with * [OAuth2ClientRequestInterceptor]. Must be registered by the - * applications themselves, no automatic bean registration + * applications themselves, there is no automatic bean registration * */ interface ClientConfigurationPropertiesMatcher { diff --git a/token-client-spring/src/main/kotlin/no/nav/security/token/support/client/spring/oauth2/DefaultOAuth2HttpClient.kt b/token-client-spring/src/main/kotlin/no/nav/security/token/support/client/spring/oauth2/DefaultOAuth2HttpClient.kt index 739bfbc0..58ff03d1 100644 --- a/token-client-spring/src/main/kotlin/no/nav/security/token/support/client/spring/oauth2/DefaultOAuth2HttpClient.kt +++ b/token-client-spring/src/main/kotlin/no/nav/security/token/support/client/spring/oauth2/DefaultOAuth2HttpClient.kt @@ -3,6 +3,7 @@ package no.nav.security.token.support.client.spring.oauth2 import org.springframework.http.HttpHeaders import org.springframework.util.LinkedMultiValueMap import org.springframework.web.client.RestClient +import org.springframework.web.client.body import no.nav.security.token.support.client.core.OAuth2ClientException import no.nav.security.token.support.client.core.http.OAuth2HttpClient import no.nav.security.token.support.client.core.http.OAuth2HttpRequest @@ -12,18 +13,15 @@ open class DefaultOAuth2HttpClient(val restClient: RestClient) : OAuth2HttpClien override fun post(request: OAuth2HttpRequest) = - restClient.post() - .uri(request.tokenEndpointUrl) - .headers { it.addAll(headers(request)) } - .body(LinkedMultiValueMap().apply { - setAll(request.formParameters) - }).retrieve() - .onStatus({ it.isError }) { _, response -> - throw OAuth2ClientException("Received $response.statusCode from $request.tokenEndpointUrl") - } - .body(OAuth2AccessTokenResponse::class.java) - - private fun headers(req: OAuth2HttpRequest): HttpHeaders = HttpHeaders().apply { req.oAuth2HttpHeaders?.let { putAll(it.headers) } } + with(request) { + restClient.post() + .uri(tokenEndpointUrl) + .headers { it.addAll(HttpHeaders().apply { putAll(oAuth2HttpHeaders.headers) }) } + .body(LinkedMultiValueMap().apply { setAll(formParameters) }) + .retrieve() + .onStatus({ it.isError }) { _, res -> throw OAuth2ClientException("Received $res.statusCode from $tokenEndpointUrl") } + .body() ?: throw OAuth2ClientException("No response from $tokenEndpointUrl") + } override fun toString() = "$javaClass.simpleName [restClient=$restClient]" } \ No newline at end of file diff --git a/token-client-spring/src/main/kotlin/no/nav/security/token/support/client/spring/oauth2/OAuth2ClientRequestInterceptor.kt b/token-client-spring/src/main/kotlin/no/nav/security/token/support/client/spring/oauth2/OAuth2ClientRequestInterceptor.kt index 44b82055..70984139 100644 --- a/token-client-spring/src/main/kotlin/no/nav/security/token/support/client/spring/oauth2/OAuth2ClientRequestInterceptor.kt +++ b/token-client-spring/src/main/kotlin/no/nav/security/token/support/client/spring/oauth2/OAuth2ClientRequestInterceptor.kt @@ -24,7 +24,7 @@ class OAuth2ClientRequestInterceptor(private val properties: ClientConfiguration private val matcher: ClientConfigurationPropertiesMatcher) : ClientHttpRequestInterceptor { override fun intercept(req: HttpRequest, body: ByteArray, execution: ClientHttpRequestExecution): ClientHttpResponse { matcher.findProperties(properties, req.uri)?.let { - service.getAccessToken(it)?.accessToken?.let { token -> req.headers.setBearerAuth(token) } + service.getAccessToken(it).accessToken?.let { token -> req.headers.setBearerAuth(token) } } return execution.execute(req, body) } diff --git a/token-validation-core/src/main/kotlin/no/nav/security/token/support/core/configuration/IssuerConfiguration.kt b/token-validation-core/src/main/kotlin/no/nav/security/token/support/core/configuration/IssuerConfiguration.kt index cb539e62..790a703e 100644 --- a/token-validation-core/src/main/kotlin/no/nav/security/token/support/core/configuration/IssuerConfiguration.kt +++ b/token-validation-core/src/main/kotlin/no/nav/security/token/support/core/configuration/IssuerConfiguration.kt @@ -9,15 +9,10 @@ import no.nav.security.token.support.core.validation.JwtTokenValidatorFactory.to open class IssuerConfiguration(val name : String, properties : IssuerProperties, val resourceRetriever : ResourceRetriever = ProxyAwareResourceRetriever()) { - val metadata : AuthorizationServerMetadata + val metadata = providerMetadata(resourceRetriever, properties.discoveryUrl) val acceptedAudience = properties.acceptedAudience val headerName = properties.headerName - val tokenValidator : JwtTokenValidator - - init { - metadata = providerMetadata(resourceRetriever, properties.discoveryUrl) - tokenValidator = tokenValidator(properties, metadata, resourceRetriever) - } + val tokenValidator = tokenValidator(properties, metadata, resourceRetriever) override fun toString() = ("${javaClass.simpleName} [name=$name, metaData=$metadata, acceptedAudience=$acceptedAudience, headerName=$headerName, tokenValidator=$tokenValidator, resourceRetriever=$resourceRetriever]") diff --git a/token-validation-core/src/main/kotlin/no/nav/security/token/support/core/configuration/IssuerProperties.kt b/token-validation-core/src/main/kotlin/no/nav/security/token/support/core/configuration/IssuerProperties.kt index 943334f8..4298dbd6 100644 --- a/token-validation-core/src/main/kotlin/no/nav/security/token/support/core/configuration/IssuerProperties.kt +++ b/token-validation-core/src/main/kotlin/no/nav/security/token/support/core/configuration/IssuerProperties.kt @@ -20,7 +20,7 @@ class IssuerProperties @JvmOverloads constructor(val discoveryUrl : URL, val usePlaintextForHttps: Boolean = false) { init { - cookieName?.let { throw IllegalArgumentException("Cookie-support is discontinued, please remove $it from ypur configuration now") } + cookieName?.let { throw IllegalArgumentException("Cookie-support is discontinued, please remove $it from your configuration now") } } override fun toString() = "IssuerProperties(discoveryUrl=$discoveryUrl, acceptedAudience=$acceptedAudience, headerName=$headerName, proxyUrl=$proxyUrl, usePlaintextForHttps=$usePlaintextForHttps, validation=$validation, jwksCache=$jwksCache)" diff --git a/token-validation-filter/src/main/kotlin/no/nav/security/token/support/filter/JwtTokenExpiryFilter.kt b/token-validation-filter/src/main/kotlin/no/nav/security/token/support/filter/JwtTokenExpiryFilter.kt index 147ced27..5f7129ff 100644 --- a/token-validation-filter/src/main/kotlin/no/nav/security/token/support/filter/JwtTokenExpiryFilter.kt +++ b/token-validation-filter/src/main/kotlin/no/nav/security/token/support/filter/JwtTokenExpiryFilter.kt @@ -14,7 +14,7 @@ import java.time.temporal.ChronoUnit.MINUTES import java.util.Date import org.slf4j.Logger import org.slf4j.LoggerFactory -import no.nav.security.token.support.core.JwtTokenConstants +import no.nav.security.token.support.core.JwtTokenConstants.TOKEN_EXPIRES_SOON_HEADER import no.nav.security.token.support.core.context.TokenValidationContextHolder import no.nav.security.token.support.core.jwt.JwtTokenClaims @@ -41,23 +41,19 @@ class JwtTokenExpiryFilter(private val contextHolder : TokenValidationContextHol override fun init(filterConfig : FilterConfig) {} - private fun addHeaderOnTokenExpiryThreshold(response : HttpServletResponse) { - val tokenValidationContext = contextHolder.getTokenValidationContext() - LOG.debug("Getting TokenValidationContext: {}", tokenValidationContext) - if (tokenValidationContext != null) { - LOG.debug("Getting issuers from validationcontext {}", tokenValidationContext.issuers) - for (issuer in tokenValidationContext.issuers) { - val jwtTokenClaims = tokenValidationContext.getClaims(issuer) - if (tokenExpiresBeforeThreshold(jwtTokenClaims)) { - LOG.debug("Setting response header {}", JwtTokenConstants.TOKEN_EXPIRES_SOON_HEADER) - response.setHeader(JwtTokenConstants.TOKEN_EXPIRES_SOON_HEADER, "true") + private fun addHeaderOnTokenExpiryThreshold(response : HttpServletResponse) = + with(contextHolder.getTokenValidationContext()) { + issuers.forEach { + if (tokenExpiresBeforeThreshold(getClaims(it))) { + response.setHeader(TOKEN_EXPIRES_SOON_HEADER, "true").also { + LOG.debug("Setting response header {}", TOKEN_EXPIRES_SOON_HEADER) + } } else { LOG.debug("Token is still within expiry threshold.") } } } - } private fun tokenExpiresBeforeThreshold(jwtTokenClaims : JwtTokenClaims) : Boolean { val expiryDate = jwtTokenClaims.get(EXPIRATION_TIME) as Date