update RemoteAuthenticationManager

- authenticate add default event on success and error
- processToken nicer catch
- makeSimpleGrantedAuthorities to add ROLE_ to role in
This commit is contained in:
2025-08-05 11:31:11 +02:00
committed by swordsteel
parent 0ee3b4d49b
commit 89f0e6d6e6

View File

@@ -10,9 +10,13 @@ import ltd.hlaeja.security.user.RemoteAuthentication
import ltd.hlaeja.security.user.RemoteUserDetail
import ltd.hlaeja.service.AccountRegistryService
import ltd.hlaeja.util.toAuthenticationRequest
import org.springframework.context.ApplicationEventPublisher
import org.springframework.security.authentication.AuthenticationServiceException
import org.springframework.security.authentication.ReactiveAuthenticationManager
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent
import org.springframework.security.authentication.event.AuthenticationSuccessEvent
import org.springframework.security.core.Authentication
import org.springframework.security.core.AuthenticationException
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.stereotype.Component
import reactor.core.publisher.Mono
@@ -23,22 +27,30 @@ private val log = KotlinLogging.logger {}
class RemoteAuthenticationManager(
private val accountRegistryService: AccountRegistryService,
private val publicJwtService: PublicJwtService,
private val publisher: ApplicationEventPublisher,
) : ReactiveAuthenticationManager {
override fun authenticate(
authentication: Authentication,
): Mono<Authentication> = accountRegistryService.authenticate(authentication.toAuthenticationRequest())
.map(::processToken)
.doOnNext { publisher.publishEvent(AuthenticationSuccessEvent(it)) }
.doOnError { ex ->
if (ex is AuthenticationException) {
publisher.publishEvent(AuthenticationFailureBadCredentialsEvent(authentication, ex))
}
}
private fun processToken(
response: ltd.hlaeja.library.accountRegistry.Authentication.Response,
): Authentication = try {
publicJwtService.verify(response.token) { claims -> makeRemoteAuthentication(claims) }
} catch (e: JwtException) {
"An error occurred while processing token: ${e.message}".let {
log.error(e) { it }
throw AuthenticationServiceException(it, e)
}
throw "An error occurred while processing token: ${e.message}"
.let {
log.error(e) { it }
AuthenticationServiceException(it, e)
}
}
private fun makeRemoteAuthentication(
@@ -53,7 +65,7 @@ class RemoteAuthenticationManager(
claims: Jws<Claims>,
): MutableList<SimpleGrantedAuthority> = (claims.payload["role"] as String)
.split(",")
.map { SimpleGrantedAuthority(it) }
.map { SimpleGrantedAuthority("ROLE_$it") }
.toMutableList()
private fun makeRemoteUserDetail(