SpringBoot solves cross-domain problems/Nginx configuration solves cross-domain problems

Solving cross-domain issues

Foreword

Cross-domain issues are an unavoidable problem in web development. We must first understand these points.

1. Cross-domain only exists with the browser and does not exist with other environments such as Android/iso/js/java and other environments.
2. Cross-domain requests can be sent, and the server can receive the request and return the result normally, but the result is intercepted by the browser.

The reason why it is cross-domain is that it is restricted by the same-origin policy. The same-origin policy is a convention and is the core and most basic security function of the browser.
Contents from the same source include: domain name, protocol, port

For security reasons, browsers must comply with the same-origin policy when using the XMLHttpRequest object to initiate HTTP requests. Otherwise, it will be a cross-domain HTTP request, which is prohibited by default. In other words, the cornerstone of browser security is the same-origin policy.

For security reasons, browsers must comply with the same-origin policy when using the XMLHttpRequest object to initiate HTTP requests. Otherwise, it will be a cross-domain HTTP request, which is prohibited by default. In other words, the cornerstone of browser security is the same-origin policy.

What is CROS?

CORS is a W3C standard, whose full name is “Cross-origin resource sharing”, which allows browsers to issue XMLHttpRequest requests to cross-origin servers, thereby overcoming the limitation that AJAX can only be used from the same origin. It adds a special Header [Access-Control-Allow-Origin] to the server to tell the client about cross-domain restrictions. If the browser supports CORS and determines that the Origin is passed, XMLHttpRequest will be allowed to initiate cross-domain requests.

CORS Header
  • Access-Control-Allow-Origin: http://localhost:8080
  • Access-Control-Max-Age: 86400
  • Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE
  • Access-Control-Allow-Headers: content-type
  • Access-Control-Allow-Credentials: true

Explanation of meaning:
1. Access-Control-Allow-Origin allows the http://localhost:8080 domain (set by yourself, only an example here) to initiate cross-domain requests.
2. Access-Control-Max-Age is set to 86400 seconds and no pre-verification request is required.
3. Access-Control-Allow-Methods sets the methods that allow cross-domain requests
4. Access-Control-Allow-Headers allows cross-domain requests to include content-type
5. Access-Control-Allow-Credentials settings allow cookies

filtr (filter) method to solve cross-domain issues

Add Filter class to the project:

package com.zx.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AllowOriginFilter implements Filter {<!-- -->
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {<!-- -->
        //TODO other processing
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {<!-- -->
// Forced conversion to httpRequest
        HttpServletRequest request = (HttpServletRequest) servletRequest;
// Forced conversion to httpResponse
        HttpServletResponse response = (HttpServletResponse) servletResponse;

// Get the Origin in the request header: origin
        String origin = request.getHeader("Origin");

        if (origin != null & amp; & amp; origin != "") {<!-- -->
            //Set response headers to allow cross-domain access
            //When requesting with cookie, it must be a full match, * cannot be used
            /**
             * Indicates that origin is allowed to initiate cross-domain requests.
             */
            response.addHeader("Access-Control-Allow-Origin", origin);

            /**
             * GET, POST, OPTIONS, PUT, DELETE represent methods that allow cross-domain requests
             */
            response.addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");

            /**
             * Indicates that there is no need to send pre-verification requests within 86400 seconds
             */
            response.addHeader("Access-Control-Max-Age", "86400");

            //Support all custom headers
            String headers = request.getHeader("Access-Control-Request-Headers");

            if (headers != null & amp; & amp; headers != "") {<!-- -->
                //Allow JSON requests and preflight command caching
                response.addHeader("Access-Control-Allow-Headers", headers);
            }

            response.addHeader("Access-Control-Max-Age", "3600");

            //Allow cookies
            response.addHeader("Access-Control-Allow-Credentials", "true");
            filterChain.doFilter(servletRequest, response);
        }

    }

    @Override
    public void destroy() {<!-- -->
        //TODO other processing
    }
}

Resolving cross-domain issues in Springboot

Two methods to solve cross-domain issues

In the SpringBoot project, convention is prioritized over configuration, and configuration is used as little as possible.

1. Inject rewrite method (WebMvcConfigurer)

To solve the problem of spanning, you only need to create an object and override its method.

The handler of the entire Application allows cross-domain

package com.zx.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CORSConfig {<!-- -->
    
    @Bean
    public WebMvcConfigurer corsConfigurer(){<!-- -->
        return new WebMvcConfigurer() {<!-- -->
            @Override
            public void addCorsMappings(CorsRegistry registry){<!-- -->
                registry.addMapping("/**") // Add mapping
                        .allowedHeaders("*") //Allowed headers
                        .allowedMethods("*") //Allowed methods
                        .allowedOrigins("*"); //Allowed origins
            }
        };
    }
}

2. @CrossOrigin

introduce:

You only need to add annotations on the interface methods that allow cross-domain methods, or you can add them directly on the Controller class to indicate that all methods of the Controller allow cross-domain access.

1. @CrossOrigin is written on the method

You can add a @crosssource annotation to the @RequestMapping .unk handler method to enable CORS on it (the default @CrossOrigin allows all origins and HTTP methods specified in the @RequestMapping annotation):

package com.zx.controller;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/admin")
public class AdminController {<!-- -->

    @CrossOrigin
    @GetMapping("/test")
    public void test(){<!-- -->
        System.out.println("Hello");
    }
}
2.@CrossOrigin is written on the class

Enable CORS for the entire controller:

package com.zx.controller;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/admin")
@CrossOrigin(origins = "http://localhost:80",maxAge = 3600)
public class AdminController {<!-- -->
    
    @GetMapping("/test")
    public void test(){<!-- -->
        System.out.println("Hello");
    }
}

Cross-domain solution in Nginx

Nginx (engine x) is a high-performance HTTP and reverse proxy web server that also provides IMAP/POP3/SMTP services.

It releases its source code under a BSD-like license and is known for its stability, rich feature set, simple configuration files, and low system resource consumption.

reverse proxy

The reverse proxy method refers to using a proxy server to accept connection requests on the Internet, then forwarding the requests to the server on the internal network, and returning the results obtained from the server to the client requesting a connection on the Internet. At this time, the proxy server appears as a reverse proxy server to the outside world.

Requirements

Confirm that the server does not handle cross-domain

Four response headers mainly involved in cross-domain
  1. Access-Control-Allow-Origin

    Used to set the source address that allows cross-domain requests (preflight requests and formal requests will be verified when cross-domain)

  2. Access-Control-Allow-Headers

    Special information fields allowed to be carried across domains (only verified in preflight requests)

  3. Access-Control-Allow-Methods

    Cross-domain allowed request methods or HTTP verbs (only preflight request verification)

  4. Access-Control-Allow-Credentials

    Whether to allow the use of cookies across domains. If you want to use cookies across domains, you can add this request response header and set the value to true (setting it or not setting it will not affect the sending of the request, but will only affect whether cookies should be carried across domains. , but if set, both preflight requests and formal requests need to be set). However, it is not recommended to use it cross-domain (it has been used in the project, but it is unstable and cannot be carried by some browsers) unless necessary, because there are many alternatives.

nginx configuration file
 upstream zx.com {
        #The weight component represents the component assigned to the port
        server localhost:8081 weight=1;
        server localhost:8082 weight=2;
        server localhost:8083 weight=3;
        server localhost:8084 weight=4;
        # backup backup backup hidden energy
        server localhost:8085 backup;
        server localhost:8086 backup;
    }

    server {
        listen 8088;
        server_name localhost;

        #charset koi8-r;

        #access_log logs/host.access.log main;

        location/{
            # Solve cross-domain issues
            add_header Access-Control-Allow-Origin *;
            add_header Access-Control-Allow-Headers X-Requested-With;
            add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
            proxy_pass http://zx.com;
        }

        # * location / {
        # root html;
        # index index.html index.htm;
        # }

        #error_page 404 /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
            roothtml;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        # proxy_pass http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        # root html;
        # fastcgi_pass 127.0.0.1:9000;
        # fastcgi_index index.php;
        # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
        #include fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        # deny all;
        #}
    }

cmd command of nginx
  1. Start the service: start nginx

  2. Exit the service: nginx -s quit

  3. Force shutdown of service: nginx -s stop

  4. Reload the service: nginx -s reload (reload the service configuration file, similar to restarting, the service will not be terminated)

  5. Verify configuration file: nginx -t

  6. Use the configuration file: nginx -c “configuration file path”

  7. Usage help: nginx -h

    Note: You can use DOS command service: you can also directly double-click nginx.exe to start the service;