OAuthSignInHandler.kt
package fr.codetics.ev_server.security
import fr.codetics.ev_server.core.AppProperties
import fr.codetics.ev_server.core.ensure
import fr.codetics.ev_server.core.msg
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import java.util.UUID
import org.springframework.security.core.Authentication
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.oauth2.core.oidc.user.OidcUser
import org.springframework.security.web.authentication.AuthenticationSuccessHandler
import org.springframework.stereotype.Component
import tools.jackson.databind.ObjectMapper
@Component
class OAuthSignInHandler(
private val accounts: AccountService,
private val properties: AppProperties,
private val json: ObjectMapper,
) : AuthenticationSuccessHandler {
override fun onAuthenticationSuccess(
request: HttpServletRequest,
response: HttpServletResponse,
authentication: Authentication,
) {
try {
val identity = authentication.principal as OidcUser
val linkedUser = linkingAccount(request)
val user =
accounts.oauth(
issuer = identity.issuer.toString(),
subject = requireNotNull(identity.subject),
email = identity.email,
name = identity.fullName ?: appleName(request),
verified = identity.claims["email_verified"]?.toString() == "true",
linkUser = linkedUser,
)
request.getSession(false)?.invalidate()
SecurityContextHolder.clearContext()
val cookie = sessionCookie(accounts.issue(user), properties.cookieSecure)
response.addHeader("Set-Cookie", cookie.toString())
response.sendRedirect("${properties.publicUrl.trimEnd('/')}/")
} catch (_: Exception) {
request.getSession(false)?.invalidate()
SecurityContextHolder.clearContext()
response.sendRedirect("${properties.publicUrl.trimEnd('/')}/auth/login?error=provider")
}
}
/**
* Apple never puts the name in the ID token: it posts it once, in the `user` form field of the very
* first sign-in (https://developer.apple.com/documentation/signinwithapple/incorporating-sign-in-with-apple-into-other-platforms).
*/
private fun appleName(request: HttpServletRequest): String? {
val user = request.getParameter("user")?.takeIf { it.length <= 2000 } ?: return null
return runCatching {
val name = json.readTree(user).path("name")
listOf(name.path("firstName").asText(""), name.path("lastName").asText(""))
.map { it.trim() }
.filter { it.isNotEmpty() }
.joinToString(" ")
.take(200)
.ifBlank { null }
}
.getOrNull()
}
private fun linkingAccount(request: HttpServletRequest): UUID? {
val session = request.getSession(false) ?: return null
val user = session.getAttribute("LINK_USER") as? UUID ?: return null
val tokenHash = session.getAttribute("LINK_TOKEN") as? String
ensure(tokenHash != null && accounts.authenticateTokenHash(tokenHash)?.id == user) {
msg("auth.oauth_origin_expired")
}
return user
}
}