Introduction to the

I’m not going to talk about cross-domain, but we’re going to go straight to the cross-domain postures, and that’s the upper postures

posture

Pose a

Implement the WebMvcConfigurer#addCorsMappings method

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 implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS") .allowCredentials(true) .maxAge(3600) .allowedHeaders("*"); }}Copy the code

Position 2

Re-inject the CorsFilter

import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; */ @configuration public class CorsFilterConfig {/** ** enable cross-domain access interceptor ** @date 2021/4/29 9:50 */ @bean public CorsFilter CorsFilter () {// Add the CorsConfiguration after creating the CorsConfiguration object CorsConfiguration = new CorsConfiguration(); / / set the release which original domain corsConfiguration. AddAllowedOrigin (" * "); / / release any original request header information corsConfiguration. AddAllowedHeader (" * "); / / release which requests way corsConfiguration. AddAllowedMethod (" * "); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); / / 2. Add the mapping path source. RegisterCorsConfiguration (" / * *, "corsConfiguration); return new CorsFilter(source); }}Copy the code

Pose three

Create a filter to resolve cross-domain

@Slf4j @Component @WebFilter(urlPatterns = { "/*" }, filterName = "headerFilter") public class HeaderFilter implements Filter { @Override public void doFilter(ServletRequest  request, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) resp; SetHeader (" access-control-allow-origin ", "*"); response.setHeader(" access-control-allow-origin ", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE"); Responsetheader (" access-Control-max-age ", "3600"); response.setHeader(" access-Control-max-age ", "3600"); response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, client_id, uuid, Authorization"); // Support HTTP 1.1.response. setHeader(" cache-control ", "no-cache, no-store, must-revalidate"); // HTTP 1.0.response. setHeader("Expires", "0") is supported; response.setHeader("Pragma", "no-cache"); / / code response. SetCharacterEncoding (" utf-8 "); chain.doFilter(request, resp); } @override public void init(FilterConfig FilterConfig) {log.info(" cross-domain filter startup "); } @override public void destroy() {log.info(" cross filter destroy "); }}Copy the code

Position 4

Use CrossOrigin annotations

It can be used on a single method or on a class

Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface CrossOrigin { /** @deprecated as Of Spring 5.0, in favor of {@link CorsConfiguration#applyPermitDefaultValues} */ @Deprecated String[] DEFAULT_ORIGINS = {"*"}; /** @deprecated as of Spring 5.0, in favor of {@link CorsConfiguration#applyPermitDefaultValues} */ @Deprecated String[] DEFAULT_ALLOWED_HEADERS = {"*"}; /** @deprecated as of Spring 5.0, in favor of {@link CorsConfiguration#applyPermitDefaultValues} */ @Deprecated boolean DEFAULT_ALLOW_CREDENTIALS = false;  /** @deprecated as of Spring 5.0, in favor of {@link CorsConfiguration#applyPermitDefaultValues} */ @Deprecated long DEFAULT_MAX_AGE = 1800; /** * Alias for {@link #origins}. */ @AliasFor("origins") String[] value() default {}; /** * A list of origins for which cross-origin requests are allowed. Please, * see {@link CorsConfiguration#setAllowedOrigins(List)} for details. * <p>By default all origins are allowed unless {@code originPatterns} is * also set in which case {@code originPatterns} is used instead. */ @AliasFor("value") String[] origins() default {}; /** * Alternative to {@link #origins()} that supports origins declared via * wildcard patterns. Please, See * @link CorsConfiguration#setAllowedOriginPatterns(List)} for details. * <p>By default this is not set. * @since 5.3  */ String[] originPatterns() default {}; /** * The list of request headers that are permitted in actual requests, * possibly {@code "*"} to allow all headers. * <p>Allowed headers are listed in the {@code Access-Control-Allow-Headers}  * response header of preflight requests. * <p>A header name is not required to be listed if it is one of: * {@code Cache-Control}, {@code Content-Language}, {@code Expires}, * {@code Last-Modified}, or {@code Pragma} as per the CORS spec. * <p>By default all requested headers are allowed. */ String[] allowedHeaders() default {}; /** * The List of response headers that the user-agent will allow the client * to access on an actual response, other than "simple" headers, i.e. * {@code Cache-Control}, {@code Content-Language}, {@code Content-Type}, * {@code Expires}, {@code Last-Modified}, or {@code Pragma}, * <p>Exposed headers are listed in the {@code Access-Control-Expose-Headers} * response header of actual CORS requests. * <p>The special value {@code "*"} allows all headers to be exposed for * non-credentialed requests. * <p>By default no headers are listed as exposed. */ String[] exposedHeaders() default {}; /** * The list of supported HTTP request methods. * <p>By default the supported methods are the same as the ones to which a * controller method is mapped. */ RequestMethod[] methods() default {}; /** * Whether the browser should send credentials, such as cookies along with * cross domain requests, to the annotated endpoint. The configured value is * set on the {@code Access-Control-Allow-Credentials} response header  of * preflight requests. * <p><strong>NOTE:</strong> Be aware that this option establishes a high * level of trust with  the configured domains and also increases the surface * attack of the web application by exposing sensitive user-specific * information such as cookies and CSRF tokens. * <p>By default this is not set in which case the * {@code Access-Control-Allow-Credentials} header is also not set and * credentials are therefore not allowed. */ String allowCredentials() default ""; /** * The maximum age (in seconds) of the cache duration for preflight responses. * <p>This property controls the value of the {@code Access-Control-Max-Age} * response header of preflight requests. * <p>Setting this to a reasonable value can reduce the number of preflight * request/response interactions required by the browser. * A negative value means <em>undefined</em>. * <p>By default this is set to {@code 1800} seconds (30 minutes). */ long maxAge() default -1;Copy the code

Have you learned all the four postures above? Learned to triple