How @PreAuthorize is working in an Reactive Application or how to live without ThreadLocal?

spring security 5
reactivesecuritycontextholder
spring webflux security
hands-on spring security 5 for reactive applications
reactive security context
hands-on spring security 5 for reactive applications pdf download
webflux securitycontextholder
spring webflux auditing

Can you explain where the advice handling @PreAuthorize("hasRole('ADMIN')") retrieves the SecurityContext in a Reactive application?

The following Spring Security example is a good illustration of this kind of usage: https://github.com/spring-projects/spring-security/tree/5.0.0.M4/samples/javaconfig/hellowebflux-method

After checking the Spring Security Webflux source code, I've found some implementations of SecurityContextRepository but the load method needs the ServerWebExchange as a parameter.

I'm trying to understand how to replace SecurityContextHolder.getContext().getAuthentication() call in a standard service (because ThreadLocal is no longer an option in a Reactive Application), but I don't understand how to replace this with a call to a SecurityContextRepository without a reference on the ServerWebExchange.

You're right, ThreadLocal is no longer an option because the processing of a request is not tied to a particular thread.

Currently, Spring Security is storing the authentication information as a ServerWebExchange attribute, so tied to the current request/response pair. But you still need that information when you don't have direct access to the current exchange, like @PreAuthorize.

The authentication information is stored in the Reactive pipeline itself (so accessible from your Mono or Flux), which is a very interesting Reactor feature - managing a context tied to a particular Subscriber (in a web application, the HTTP client is pulling data from the server and acts as such).

I'm not aware of an equivalent of SecurityContextHolder, or some shortcut method to get the Authentication information from the context.

See more about Reactor Context feature in the reference documentation. You can also see an example of that being used in Spring Security here.

Spring Security Context Propagation with @Async, How @PreAuthorize is working in an Reactive Application or how to live without ThreadLocal? How the bean's container discover your configuration? In your application you have a servlet configuration (part of the web context) and you have the application context (or the root context) which contains persistence configuration, security configuration, etc – akuma8 Jun 14 '17 at 12:35

The ReactiveSecurityContextHolder provides the authentication in a reactive way, and is analogous to SecurityContextHolder.

Its getContext() method provides a Mono<SecurityContext>, just like SecurityContextHolder.getContext() provides a SecurityContext.

ReactiveSecurityContextHolder
                    .getContext()
                    .map(context ->
                            context.getAuthentication()

Spring Security Reference, is bound to a ThreadLocal – so, when the execution flow runs in a new thread with @Async, that's not going to be an authenticated context. 4. Prevent Method call without Exception using @PreAuthorize Annotation stackoverflow.com. We are using Spring Security 3. We have a custom implementation of PermissionEvaluator that has this complex algorithm to grant or deny access at method level on the application.

I implemented a JwtAuthenticationConverter (kotlin):

@Component
class JwtAuthenticationConverter : Function<ServerWebExchange, 
Mono<Authentication>> {

@Autowired
lateinit var jwtTokenUtil: JwtTokenUtil

@Autowired
lateinit var userDetailsService: ReactiveUserDetailsService

private val log = LogFactory.getLog(this::class.java)

override fun apply(exchange: ServerWebExchange): Mono<Authentication> {
    val request = exchange.request

    val token = getJwtFromRequest(request)

    if ( token != null )
        try {
            return userDetailsService.findByUsername(jwtTokenUtil.getUsernameFromToken(token))
                    .map { UsernamePasswordAuthenticationToken(it, null, it.authorities) }
        } catch ( e: Exception ) {
            exchange.response.statusCode = HttpStatus.UNAUTHORIZED
            exchange.response.headers["internal-message"] = e.message
            log.error(e)
        }

    return Mono.empty()
}

private fun getJwtFromRequest(request: ServerHttpRequest): String? {
    val bearerToken = request.headers[SecurityConstants.TOKEN_HEADER]?.first {
        it.startsWith(SecurityConstants.TOKEN_PREFIX, true)}
    return if (bearerToken.isNullOrBlank()) null else bearerToken?.substring(7, bearerToken.length)
}

And then I set a SecurityConfig like this:

val authFilter = AuthenticationWebFilter(ReactiveAuthenticationManager {
    authentication: Authentication -> Mono.just(authentication)
})
authFilter.setAuthenticationConverter(jwtAuthenticationConverter)

http.addFilterAt( authFilter, SecurityWebFiltersOrder.AUTHENTICATION)

You can use this approach to customize your AuthenticationConverter as I did to jwt based authentication to set the desired authentication object.

spring-projects/spring-security, Testing Reactive Method Security; 30.2. I can't get LDAP authentication to work​. to Maven Central, so no additional Maven repositories need to be declared in When a user tried to authenticate, the hashed password would be compared to Some applications aren't entirely suitable for using a ThreadLocal , because  Reactive applications We believe that all necessary aspects are already recognised individually: we want systems that are responsive, resilient, elastic and message driven. We call these Reactive Systems. There is no need for a HTTP server. The application is using one single process. PHP and the database (SQLite) are running inside this process.

Spring Method Security with @PreAuthorize and @Secured , @philsttr using both would imply that you are trying to use a reactive And it would be super awesome if @PreAuthorize worked in that old synchronous code. why spring security jwt is not mentioned in the documentation ? My team with to upgrade the application to spring boot 2.1.9 and java 11 and  How To Pass Context Between Layers With ThreadLocal And EJB 3.(1) TransactionSynchronizationRegistry is the way to go - you don't have to worry about the existence of

Securing Java gRPC services with Spring , This security can be applied to multiple levels in your web application. learn to apply method security using annotations such as @PreAuthorize and @Secured . To test above annotations in running application, I am using the code base of If user has not this authority, an access denied exception will be thrown. How to make AuditorAware work with Spring Data Mongo Reactive. work. Currently I can not find a Reactive an Reactive Application or how to live without

Spring Boot 2, To apply granular authorization requirements to each gRPC service method, we Security uses a number of components to make method-based security work. However, the gRPC Java runtime is based on netty, not servlets. Our security context persistence interceptor won't be as general as Spring  Previous Next Hello Friends!!! In this tutorial we will discuss the Spring Security with Spring Boot and also will see an example based on Spring security with Spring Boot. 1. Spring security Overview Spring security is the highly customizable authentication and access-control framework. This is the security module for securing spring applications. But, this can also be used for non-spring

Comments