Khilarian
Khilarian

Reputation: 251

How to connect reactive spring security with jpa database

I want to get some self user info from non-reactive database with reactive spring security support. With non-reactive security it was easy, like

var customUserDto = Optional.ofNullable(getCurrentUserAuthentication()).map(Authentication::getPrincipal)
                .filter(CustomUserDetails.class::isInstance).map(CustomUserDetails.class::cast).orElse(null);

I tried do the same next way:

String username = ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication)getCurrentUserAuthentication().map(Authentication::getName);
var userInfo = userInfoRepository.findByEmail(username.block()).orElse(null);

but it failed on the last line with "block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-epoll-2"

Can it be solved or I should use all non-reactive spring because of DB? Thanks in advance.

Upvotes: 0

Views: 42

Answers (1)

SledgeHammer
SledgeHammer

Reputation: 7736

Spring Webmvc uses Jdbc which is synchronous. Spring Webflux is reactive and as you've seen, you can't have blocking I/O in Webflux as that defeats the whole point.

You can "fake it" by wrapping your blocking calls in a Mono.fromCallable(), but that's not really recommended and really defeats the purpose of Webflux and you might as well go to Java 21 / virtual threads / webmvc at that point.

If you have a flat table, then it is pretty trivial to make your database reactive using R2dbc instead of Jdbc. R2dbc is a primitive low level driver, so you're on your own if you want relationships between your tables. HIBERNATE DOES NOT SUPPORT R2DBC.

There is a newer reactive Hibernate, that also does NOT support r2dbc, but rather the Vert.x driver. This also requires using a Mutiny shim since reactive Hibernate doesn't support Webflux directly.

There are samples out there of using Vert.x + Reactive Hibernate + a Mutiny shim in a Spring Webflux application, but they are rather trivial implementations. A full fledged implementation is non-trivial. I'm doing that myself now actually.

Upvotes: 0

Related Questions