Angular 2 Spring Boot Login CORS Problems

前端 未结 2 1937
星月不相逢
星月不相逢 2020-12-03 19:48

I am trying to develop an application with Spring Boot for the back end and Angular 2 for the front end.

Actually i have connection problems, when i accessing on the

相关标签:
2条回答
  • 2020-12-03 20:42

    First thing you need to understand Cors configuration is added in the backend. You do not need to send cors header with each request from Angular2 App. Understanding that, this problem is easily fixed by adding global CORS configuration in your spring security configuration class.

    First you need to create a filter bean :

    @Component
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public class MyCorsFilter implements Filter{
    
    public MyCorsFilter () {
        super();
    }
    
    @Override
    public final void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException {
        final HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
    
        // without this header jquery.ajax calls returns 401 even after successful login and SSESSIONID being succesfully stored.
        response.setHeader("Access-Control-Allow-Credentials", "true");
    
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Authorization, Origin, Content-Type, Version");
        response.setHeader("Access-Control-Expose-Headers", "X-Requested-With, Authorization, Origin, Content-Type");
    
        final HttpServletRequest request = (HttpServletRequest) req;
        if (!request.getMethod().equals("OPTIONS")) {
            chain.doFilter(req, res);
        } else {
            // do not continue with filter chain for options requests
        }
    }
    
    @Override
    public void destroy() {
    
    } 
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {       
    }
    }
    

    STEP 2: In your spring security configuration class add :

    @Autowired
    private MyCorsFilter myCorsFilter;
    
    
    //CORS
    http.addFilterBefore(myCorsFilter, ChannelProcessingFilter.class);
    

    EDIT : This configuration assumes you have angular2 app running at localhost:3000

    0 讨论(0)
  • 2020-12-03 20:52

    In case, you are working with Spring 4.2 and further releases, there is a firstclass support for CORS out-of-the-box. Read this page.

    You could get away by defining following annotation at the class level:

    @CrossOrigin(origins = "http://localhost:3000", maxAge = 3600)
    
    0 讨论(0)
提交回复
热议问题