Skip to content

Commit

Permalink
added further logging and debugging to help understand logic
Browse files Browse the repository at this point in the history
  • Loading branch information
ivanskodje committed Apr 16, 2024
1 parent dacf51d commit 76e63e0
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 31 deletions.
Empty file.
61 changes: 31 additions & 30 deletions ebms-provider/src/main/kotlin/no/nav/emottak/ebms/HttpClients.kt
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,15 @@ import io.ktor.http.Parameters
import io.ktor.http.auth.HttpAuthHeader
import io.ktor.http.contentType
import io.ktor.serialization.kotlinx.json.json
import io.ktor.server.auth.Authentication
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import no.nav.emottak.ebms.auth.AuthConfig
import no.nav.emottak.ebms.auth.LENIENT_JSON_PARSER
import no.nav.emottak.melding.model.PayloadRequest
import no.nav.emottak.melding.model.PayloadResponse
import no.nav.emottak.melding.model.SendInRequest
Expand Down Expand Up @@ -114,31 +116,34 @@ class ClientCredentialsProvider(private val httpClient: HttpClient) : AuthProvid
private val scope = AuthConfig.getEbmsSendInScope()
private val tokenUrl = AuthConfig.getAzureTokenEndpoint()

private var currentToken: String? = null
private var currentToken: BearerTokens? = null
private val mutex = Mutex()

override val sendWithoutRequest: Boolean = true
override fun isApplicable(auth: HttpAuthHeader): Boolean = true
override suspend fun addRequestHeaders(request: HttpRequestBuilder, authHeader: HttpAuthHeader?) {
log.debug("Adding token to headers!")
val token = getToken()
request.headers.append(HttpHeaders.Authorization, "Bearer $token")
if(shouldAuthenticate(request.url.toString())) {
log.debug("Adding token to headers for URL: ${request.url}")
val token = getToken()
request.headers.append(HttpHeaders.Authorization, "Bearer $token")
} else {
log.debug("Wont add auth to header to URL: ${request.url}");
}
}

private fun shouldAuthenticate(url: String): Boolean {
return url.endsWith("ebms-send-in/")
}

private suspend fun getToken(): String = mutex.withLock {
private suspend fun getToken(): BearerTokens = mutex.withLock {
currentToken ?: refreshToken()
}

override suspend fun refreshToken(response: HttpResponse): Boolean = mutex.withLock {
if (response.status == HttpStatusCode.Unauthorized) {
log.debug("Attempting to refresh token after receiving a 401 response")
try {
val newToken = refreshToken()
if (newToken.isEmpty()) {
log.error("Was unable to fetch a refresh token")
return false
}
currentToken = newToken
refreshToken()
return true
} catch (ex: Exception) {
log.error("Failed to refresh token: ${ex.message}")
Expand All @@ -147,27 +152,23 @@ class ClientCredentialsProvider(private val httpClient: HttpClient) : AuthProvid
return false
}

private suspend fun refreshToken(): String {
val parameters = Parameters.build {
append("client_id", clientId)
append("client_secret", clientSecret)
append("scope", scope)
append("grant_type", "client_credentials")
}
val tokenResponse: String = httpClient.post(tokenUrl) {
header("Content-Type", "application/x-www-form-urlencoded")
setBody(FormDataContent(parameters))
}.bodyAsText()
private suspend fun refreshToken(): BearerTokens {
val requestBody = "client_id=$clientId&client_secret=$clientSecret&scope=$scope&grant_type=client_credentials"
log.debug("REMOVE ME: refreshToken(): RequestBody clientId: $clientId scope: $scope")

val accessToken = Json.parseToJsonElement(tokenResponse).jsonObject["access_token"]!!.jsonPrimitive.content
val parsedJwt = SignedJWT.parse(accessToken)
val accessToken: BearerTokens = httpClient.post(tokenUrl) {
header("Content-Type", "application/x-www-form-urlencoded")
setBody(requestBody)
}.bodyAsText() .let { tokenResponseString ->
SignedJWT.parse(
LENIENT_JSON_PARSER.decodeFromString<Map<String, String>>(tokenResponseString)["access_token"] as String
)
}
.let { parsedJwt ->
BearerTokens(parsedJwt.serialize(), "ignoredRefreshToken")
}

currentToken = accessToken

return parsedJwt.serialize()
}
fun createBearerTokens(): BearerTokens = runBlocking {
val accessToken = refreshToken()
BearerTokens(accessToken, "ignoredRefreshToken")
return accessToken
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import kotlinx.serialization.json.Json
import no.nav.emottak.ebms.log
import no.nav.emottak.util.getEnvVar

private val LENIENT_JSON_PARSER = Json {
val LENIENT_JSON_PARSER = Json {
isLenient = true
}

Expand Down

0 comments on commit 76e63e0

Please sign in to comment.