1

I have created one app using angular and springboot for basic authentication with spring security but i am getting 401 error ..i am novice in springboot

@Configuration
@EnableWebSecurity
public class SpringSecurityConfigurationBasicAuth extends WebSecurityConfigurerAdapter{ 

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
                .anyRequest().authenticated()
                .and()
            //.formLogin().and()
            .httpBasic();
    }
}

"Access to XMLHttpRequest at 'http://localhost:8080/hello-world/path-variable/MSD' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status."

Patrick W
  • 1,485
  • 4
  • 19
  • 27
MONI SHANKAR
  • 11
  • 1
  • 1
  • 3
  • Which plugin should i add?? – MONI SHANKAR Jul 09 '19 at 06:17
  • 2
    You shouldn't add any chrome plugin. EIther your backend API is indeed supposed, once in production, to be called from other domains/ports, and you should add CORS support on your backend API, or it shouldn't, and your development environment should thus mimic the production environment by serving the backend and the frontend from the same host/port. You typically do that by using the Angular CLI server as a proxy to your backend API. https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md – JB Nizet Jul 09 '19 at 06:21
  • @Sachi.Dila don't suggest solutions that compromise someones web security without warning them. When you install a cors plugin, you allow any site to access any other site including allowing access to gmail.com from attacker.example.com. There have been attacks like this in the past for the careless developers who don't understand why a certain protection is in place – Ferrybig Jul 09 '19 at 06:26
  • AFAIR when you want to allow authenticated access from different origins and these requests not being stopped by your browser, your backend must explicitely "allow" these origins telling the browser via the "Access-Control-Allow-Origin" header listing the allowed origins. – Smutje Jul 09 '19 at 06:27
  • @MONI SHANKAR please try using my code I think it solves your issue. – Ganesh Gudghe Jul 09 '19 at 06:49

2 Answers2

0

I also had the same issue with angulat7 and spring boot I resolved by adding the following configuration

 @Configuration
    public class SpringDataRestConfiguration extends RepositoryRestConfigurerAdapter {

        @Override
        public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {

        config.getCorsRegistry().addMapping("/**").allowedOrigins("*").allowedHeaders("*").allowedMethods("GET", "POST", "PATCH", "PUT", "DELETE");
        }

    }
Ganesh Gudghe
  • 1,327
  • 1
  • 17
  • 41
  • Does this work with authentication? Last time I checked, a "*" allowed origin is interpreted from browsers as "insecure" and thus does not allow authentication headers being sent. – Smutje Jul 09 '19 at 06:25
  • I refer to https://stackoverflow.com/questions/19743396/cors-cannot-use-wildcard-in-access-control-allow-origin-when-credentials-flag-i – Smutje Jul 09 '19 at 06:28
0

You could try the following At the top of the controller, you can add @CrossOrigin(origins = "*", allowedHeaders = "*") or customise if required

...
@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestController
public class UserController {
    // Methods
}
...

Please try above solution and let me know if this doesnt work

EDIT 1: You could also try to create a filter with CORS options:

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(1)
public class SimpleCORSFilter implements Filter {

    private final Logger log = LoggerFactory.getLogger(SimpleCORSFilter.class);

    public SimpleCORSFilter() {
        log.info("SimpleCORSFilter init");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {

        // HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");

        chain.doFilter(req, res);
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {
    }

}

Please try with the filters method and let me know if it doesn't work

Sagar Chilukuri
  • 1,430
  • 2
  • 17
  • 29
  • @CrossOrigin(origins = "http://localhost:4200") @RestController public class HelloWordlController { @GetMapping(path = "/hello-world") public String helloWorld() ...... That part i already added and i tried with ur code as well but it is not working bro – MONI SHANKAR Jul 09 '19 at 06:35
  • @MONISHANKAR have you added the allowance of credentials? Otherwise your browser won't send any. – Smutje Jul 09 '19 at 06:39
  • @MONISHANKAR, added `filters` based solution. Please check once – Sagar Chilukuri Jul 09 '19 at 06:40
  • @SagarCh thanks for ur code but i think ur code is related servlet and m using angular7 with springboot security..M not sure whether it will work or not.. – MONI SHANKAR Jul 09 '19 at 06:46