Home > Software engineering >  Why can't my Postman find my Spring REST API?
Why can't my Postman find my Spring REST API?

Time:09-05

I am doing simple request of getting one user by id by Postman. But response status is 200 and it is not returning anything. However in my user table I have data. I thought that problem is with antMatchers but couldnt manage it. There is no log data in the console. i can access to other controllers but with this user controller there is a problem. Why am I not able to connect to my backend?

Postman

SecurityConfig

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private UserDetailsServiceImpl userDetailsService;

    private JwtAuthenticationEntryPoint handler;

    public SecurityConfig(UserDetailsServiceImpl userDetailsService, JwtAuthenticationEntryPoint handler) {
        this.userDetailsService = userDetailsService;
        this.handler = handler;
    }

    /*@Bean
    public JwtAuthenticationFilter jwtAuthenticationFilter() {
        return new JwtAuthenticationFilter();
    }*/

    @Bean(BeanIds.AUTHENTICATION_MANAGER)
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

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

    @Override
    public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOriginPattern("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("HEAD");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("PATCH");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

    @Override
    public void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .cors()
                .and()
                .csrf().disable()
                .exceptionHandling().authenticationEntryPoint(handler).and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests()
                .antMatchers(HttpMethod.GET, "/type")
                .permitAll()
                .antMatchers(HttpMethod.GET, "/nation")
                .permitAll()
                .antMatchers(HttpMethod.GET, "/recept")
                .permitAll()
                .antMatchers(HttpMethod.GET, "/recept/**")
                .permitAll()
                .antMatchers(HttpMethod.GET, "/ingredient")
                .permitAll()
                .antMatchers(HttpMethod.GET, "/recept/{\\\\d }")
                .permitAll()
                .antMatchers("/users/**")
                .permitAll()
                .antMatchers("/auth/**")
                .permitAll()
                .anyRequest().authenticated();

        httpSecurity.addFilterBefore(new JwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }
}

UserController

@Slf4j
@RestController
public class UserController {

    private UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }


    @RequestMapping(value="/users",method= RequestMethod.GET, headers = "Accept=application/json")
    public List<UserResponse> getAllUsers(){
        return userService.getAllUsers().stream().map(u -> new UserResponse(u)).collect(Collectors.toList());
    }


    @RequestMapping(value="/users",method= RequestMethod.POST, headers = "Accept=application/json")
    public ResponseEntity<Void> createUser(@RequestBody User newUser) {
        User user = userService.saveOneUser(newUser);
        if(user != null)
            return new ResponseEntity<>(HttpStatus.CREATED);
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @RequestMapping(value="/users/{userId}",method= RequestMethod.GET, headers = "Accept=application/json")
    public UserResponse getOneUser(@PathVariable Long userId) {
        log.info (String.valueOf (userId));
        User user = userService.getOneUserById(userId);
        if(user == null) {
            throw new UserNotFoundException ();
        }
        return new UserResponse(user);
    }

    @RequestMapping(value="/users/{userId}",method= RequestMethod.PUT, headers = "Accept=application/json")
    public ResponseEntity<Void> updateOneUser(@PathVariable Long userId, @RequestBody User newUser) {
        User user = userService.updateOneUser(userId, newUser);
        if(user != null)
            return new ResponseEntity<>(HttpStatus.OK);
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);

    }

    @RequestMapping(value="/users/{userId}",method= RequestMethod.DELETE, headers = "Accept=application/json")
    public void deleteOneUser(@PathVariable Long userId) {
        userService.deleteById(userId);
    }

}

UserResponse

@Data
public class UserResponse {

    Long id;
    int avatarId;
    String userName;

    public UserResponse(User entity) {
        this.id = entity.getId();
        this.avatarId = entity.getAvatar();
        this.userName = entity.getUser_name ();
    }
}

CodePudding user response:

I thing you need to add the word 'api' in your http request, for example http://localhost:8080/api/users.

CodePudding user response:

1/ Any JUnit5 tests implemented to get automatisation testing for these kind of stuff.

2/ With postman you are using the port 8081, have you checked it in your application-{env}.properties twice ?

3/ Your are using JwtAuthenticationFilter did you configure properly your roles and users to authenticate yourself correctly.

4/ Did you checked your Bearer generated :

Bearer = Base64EncodedString(username:password); 
//Or a valid JWT token get with another authentication method, of course.

5/ You are not using any Spring Security annotation to access to your controller which is located inside a protected area by default. Look at @PreAuthorize and @Secured annotations or alternatives. Do not forget to activate them with @EnableWebSecurity in your Security configuration class (ie WebSecurityConfig.java or like).

  • Related