-1

I am using Spring-boot config for basic-auth and when I am trying to access the http://192.168.0.3/v1 using credentials, I am getting CORS error, even though I have configurations for CORS. The weird thing is, when I am accessing the http://192.168.0.3/v1/signup, I am able to create a user. why CORS error for the root url access only?

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
@ComponentScan(basePackages = { "com.ofloy.rest.security" })
@Import({CorsConfig.class})
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .authorizeRequests()
        .antMatchers("/signup/**").permitAll()
        .anyRequest().authenticated()
        .and().httpBasic()
        .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and().csrf().disable()
        ;
    }
}

@Configuration
public class CorsConfig {

    @Bean
    public FilterRegistrationBean<Filter> customCorsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");

        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<Filter>(new CorsFilter(source));
        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return bean;
    }
}

I am using UserDetailsService for querying the real user from my DB and set server.servlet.context-path = /v1/

Basically two issues I am facing with the above configuration:

  1. I am able to access http://192.168.0.3/v1/signup but not http://192.168.0.3/v1/ from the broweser, as getting CORS error.
  2. Accessing http://192.168.0.3/v1(from POSTMAN) using the credentials to check if the credentials are correct, give me the 404 error. 404 if credentials are correct and 401 is not correct. Why 404?

Note: One thing I have noticed for second issues is, even if I send the POST request to http://192.168.0.3/v1, the spring Logs shows it GET request, here is the log stack.

DEBUG DispatcherServlet : GET "/v1/", parameters={}
WARN PageNotFound : No mapping for GET /v1/
DEBUG DispatcherServlet : Completed 404 NOT_FOUND DEBUG DispatcherServlet : "ERROR" dispatch for GET "/v1/error", parameters={}
DEBUG RequestMappingHandlerMapping : Mapped to public org.springframework.http.ResponseEntity org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest) DEBUG HttpEntityMethodProcessor : Using 'application/json', given
[/] and supported [application/json, application/*+json]
DEBUG HttpEntityMethodProcessor : Writing [{timestamp=Wed Jan 30 16:16:40 IST 2019, status=404, error=Not Found, message=No message available, path=/v1/}]
DEBUG DispatcherServlet : Exiting from "ERROR" dispatch, status 404

UPDATE: this is the CORS error in browser

Access to XMLHttpRequest at 'http://192.168.43.70:8085/v1' from origin 'http://localhost:3007' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

The Coder
  • 3,447
  • 7
  • 46
  • 81
  • *Accessing http://192.168.0.3/v1(from POSTMAN) using the credentials to check if the credentials are correct, give me the 404 error. 404 if credentials are correct and 401 is not correct. Why 404?* That is no CORS issue. You have no controller for that URL, hence you get 404 Not found error. – dur Jan 30 '19 at 11:22
  • 3
    Possible duplicate of [CORS issue - No 'Access-Control-Allow-Origin' header is present on the requested resource](https://stackoverflow.com/questions/42016126/cors-issue-no-access-control-allow-origin-header-is-present-on-the-requested) – dur Jan 30 '19 at 13:24
  • You didn't configure CORS in your Spring Security configuration, you have to add `http.cors()`. – dur Jan 30 '19 at 13:25
  • @dur Updated the question details for CORS error. For 404, why do I need a controller for the root URL? That doesn't make any sense. Shouldn't the spring security handle it in some other way? I am sending credentials to http://192.168.0.3/v1 from the login page of my web, if the server sends a status ok(user details are correct), then I will save the credentials into browser. – The Coder Jan 30 '19 at 13:26
  • Yes, because your are calling a URL and this URL have to return a response. If you don't map a JSP/HTML or a controller you get a 404 Not found. In case of HTTP basic authentication there is no authentication endpoint, you are sending the credentials with every request. – dur Jan 30 '19 at 13:33
  • Getting back to your CORS issue. `http.cors()` is needed. I don't see your Spring MVC configuration, but I guess your CORS configuration is used in Spring MVC. That's the reason your public endpoints are working. But your secured endpoints are sending credentials, that's the reason your browser is sending the preflight request. – dur Jan 30 '19 at 13:37
  • You didn't expose your CORS configuration, you only exposed a servlet filter. That's propably the reason. Use the CORS configuration in the other question's answer: `@Bean CorsConfigurationSource corsConfigurationSource()` – dur Jan 30 '19 at 13:41
  • I imported the the CORS config class to the security config class. `@Import({CorsConfig.class})`. I tried to access a protected resource(as you predicted that this is the issue with protected ones). And There is no CORS error with any protected resource. – The Coder Jan 30 '19 at 13:47
  • @dur added `http.cors()` and Bean `corsConfigurationSource()`. Still same issue. – The Coder Jan 30 '19 at 14:00
  • *I tried to access a protected resource(as you predicted that this is the issue with protected ones). And There is no CORS error with any protected resource.* What does that mean? You wrote that you have a CORS issue (1) if you access `http://192.168.0.3/v1/` and that URL is protected. – dur Jan 30 '19 at 14:03
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/187576/discussion-between-thecoder-and-dur). – The Coder Jan 30 '19 at 14:05

1 Answers1

0

I would do something like below on the controller which handles the request:

@CrossOrigin(origins = "http://localhost:3007")
@RestController
@RequestMapping("/v1")
public class VoneController {
Simon
  • 925
  • 3
  • 13
  • 30