Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually set authentication with ReactiveSecurityContextHolder

Tags:

I'm trying to setup Spring Security with Spring Web Flux. I don't understand how to manually set the SecurityContext with ReactiveSecurityContextHolder. Do you have any resource or hint? Take for example this filter I've written that reads a JWT token and needs to set the authentication manually:

@Slf4j
public class JwtTokenAuthenticationFilter implements WebFilter {

    private final JwtAuthenticationConfig config;

    private final JwtParser jwtParser = Jwts.parser();

    public JwtTokenAuthenticationFilter(JwtAuthenticationConfig config) {
        this.config = config;
        jwtParser.setSigningKey(config.getSecret().getBytes());
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {

        String token = exchange.getRequest().getHeaders().getFirst(config.getHeader());
        if (token != null && token.startsWith(config.getPrefix() + " ")) {
            token = token.replace(config.getPrefix() + " ", "");
            try {
                Claims claims = jwtParser.parseClaimsJws(token).getBody();
                String username = claims.getSubject();
                @SuppressWarnings("unchecked")
                List<String> authorities = claims.get("authorities", List.class);
                if (username != null) {
                    UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(username, null,
                            authorities.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()));

                    // TODO set authentication into ReactiveSecurityContextHolder 
                }
            } catch (Exception ex) {
                log.warn(ex.toString(), ex);
                ReactiveSecurityContextHolder.clearContext();
            }
        }
        return chain.filter(exchange);
    }
}
like image 566
Alessandro Dionisi Avatar asked Apr 03 '19 15:04

Alessandro Dionisi


1 Answers

I managed to update the SecurityContext by calling:

return chain.filter(exchange).subscriberContext(ReactiveSecurityContextHolder.withAuthentication(auth));

Correct me if I'm wrong or if there is a better way to manage it.

like image 73
Alessandro Dionisi Avatar answered Sep 28 '22 04:09

Alessandro Dionisi