RestTemplate/WebClient request call on Spring Security Application

Okay, so I need to make cucumber integration tests. My application is Spring Security Application which uses JwtTokens and checks it with custom filter.

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

    public static final AntPathRequestMatcher REQUEST_MATCHER_LOGIN = new AntPathRequestMatcher("/auth/login");
    public static final AntPathRequestMatcher REQUEST_MATCHER_TRAINEE_CREATE = new AntPathRequestMatcher("/trainee/create");
    public static final AntPathRequestMatcher REQUEST_MATCHER_TRAINER_CREATE = new AntPathRequestMatcher("/trainer/create");
    public static final String LOGOUT_URL = "/auth/logout";
    private final JwtFilter jwtFilter;
    private final LogoutHandler logoutHandler;

    @Autowired
    public WebSecurityConfig(JwtFilter jwtFilter, @Lazy LogoutHandler logoutHandler) {
        this.jwtFilter = jwtFilter;
        this.logoutHandler = logoutHandler;
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .cors(Customizer.withDefaults())
                .authorizeHttpRequests(request -> request
                        .requestMatchers(REQUEST_MATCHER_LOGIN).permitAll()
                        .requestMatchers(REQUEST_MATCHER_TRAINEE_CREATE).permitAll()
                        .requestMatchers(REQUEST_MATCHER_TRAINER_CREATE).permitAll()
                        .anyRequest().authenticated())
                .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
                .csrf(AbstractHttpConfigurer::disable)
                .logout(logout -> {
                    logout.logoutUrl(LOGOUT_URL);
                    logout.addLogoutHandler(logoutHandler);
                    logout.logoutSuccessHandler(((request, response, authentication) ->
                            SecurityContextHolder.clearContext())
                    );
                });

        return http.build();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    @Bean
    public PasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public TimedAspect timedAspect(MeterRegistry registry) {
        return new TimedAspect(registry);
    }

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule()); // Register JSR310 module
        return objectMapper;
    }

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

So, when I call it let’s say from different service, it throws 403 [no body] error.
Here is my code where I make put request on my spring security app with webclient, but it still give same error. The same result is with RestTemplate.

WebClient webClient = WebClient.builder().baseUrl(BASE_URL).defaultHeader(HttpHeaders.USER_AGENT, "Application").defaultHeader(HttpHeaders.ACCEPT, MediaType.ALL_VALUE).defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).defaultHeader(HttpHeaders.AUTHORIZATION, getToken()).build();

TraineeDto responseTraineeDto = webClient.put().uri("/trainee/update").body(BodyInserters.fromValue(updateTraineeDto)).retrieve().bodyToMono(TraineeDto.class).block();

  • Why have you built a custom filter of something that already exists in spring security. And is the JWT coming from a browser, because that is very dangerous. Please dont just read a bad tutorial and when it doesnt work you ask here. Please do some research of what features are included in spring security and learn to use the documentation. And also learn to debug and read your debug logs and include debug logs in your question.

    – 




Leave a Comment