How to create and persist a custom user object before endpoint execution in webflux?

135 views Asked by At

I am currently developing an OAuth 2.0 resource server (REST API) with Spring Webflux.

I have Spring Security set up and I can successfully authenticate users with Spring's built-in principal class.

The problem:

The application needs to store additional information about the user as per requirement. Users that access the API for the first time are not stored in the REST API's internal user database. Right now I have to check if the provided principal name (I have access to the respective OAuth UUID - the one stored in the authorization server) already exists in the application database.

I would like to avoid code duplication, where I would have to call a method that does exactly that on every endpoint

Here is what already works:

@GetMapping("/secure")
fun secureEndpoint(principal: Principal): ResponseEntity<Void> {
    println(principal.name)
    // here I would have to check if the user has already been
    // created in the database
    return ResponseEntity.ok().build()
}

As I said, the principals correct UUID is already being displayed. What I am looking for is some kind of webfilter, that runs before every (authenticated) endpoint, and automatically creates the user, so I do not have to do it in the controller layer.

This is my Security configuration:

@Bean
fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
    val cookieServerCsrfTokenRepository = CookieServerCsrfTokenRepository()
    cookieServerCsrfTokenRepository.setCookieHttpOnly(false)


    http.authorizeExchange()
        .pathMatchers("/**").permitAll()
        .pathMatchers("/secure/**").authenticated()
        .and()
        .oauth2ResourceServer()
        .jwt()

    http.csrf()
        .csrfTokenRepository(cookieServerCsrfTokenRepository)


    return http.build()
}

I would greatly appreciate any help!

0

There are 0 answers