上海做网站的公司哪家好,沧州建设银行招聘网站,如何选择企业网站开发,建设工程标准合同范本目录 1、跨域概念2、后端CORS#xff08;跨域资源共享#xff09;配置原理3、既然请求跨域了#xff0c;那么请求到底发出去没有#xff1f;4、通过后端CORS#xff08;跨域资源共享#xff09;配置解决跨域问题代码4.1、SpringBoot#xff08;FilterRegistrationBean跨域资源共享配置原理3、既然请求跨域了那么请求到底发出去没有4、通过后端CORS跨域资源共享配置解决跨域问题代码4.1、SpringBootFilterRegistrationBean4.1.1、配置文件4.1.2、项目4.1.3、结果验证 4.2、SpringBootWebMvcConfigurer4.2.1、配置文件4.2.2、项目4.2.3、结果验证 4.3、SpringBootCrossOrigin4.3.1、使用示例4.3.2、项目4.3.3、结果验证 4.4、SpringBootSpringSecurity 过滤器4.4.1、配置文件4.4.2、项目 4.5、SpringCloud-GatewayCorsWebFilter4.5.1、配置文件4.5.2、项目4.5.3、结果验证 4.6、SpringCloud-GatewayWebFilter4.6.1、配置文件4.6.2、项目4.6.3、结果验证 4.7、SpringCloud-Gatewaybootstrap.yml4.7.1、配置文件bootstrap.yml4.7.2、项目4.7.3、结果验证 1、跨域概念
通过一个地址去访问另外一个地址两个地址的url中的3个地方只要有任何一个不同那就会引起跨域问题它们分别是访问协议、ip地址、端口号
日常工作中用得比较多的解决跨域方案是Nginx代理或者后端CORS跨域资源共享配置
2、后端CORS跨域资源共享配置原理
CORS 需要浏览器和后端同时支持。IE 8 和 9 需要通过 XDomainRequest 来实现。 浏览器会自动进行 CORS 通信实现 CORS 通信的关键是后端。只要后端实现了 CORS就实现了跨域。
服务端设置 Access-Control-Allow-Origin 就可以开启 CORS。 该属性表示哪些域名可以访问资源如果设置通配符则表示所有网站都可以访问资源。
3、既然请求跨域了那么请求到底发出去没有
跨域并不是请求发不出去请求能发出去服务端能收到请求并正常返回结果只是结果被浏览器拦截了。你可能会疑问明明通过表单的方式可以发起跨域请求为什么 Ajax 就不会?因为归根结底跨域是为了阻止用户读取到另一个域名下的内容Ajax 可以获取响应浏览器认为这不安全所以拦截了响应。但是表单并不会获取新的内容所以可以发起跨域请求。同时也说明了跨域并不能完全阻止 CSRF因为请求毕竟是发出去了。
4、通过后端CORS跨域资源共享配置解决跨域问题代码
4.1、SpringBootFilterRegistrationBean
4.1.1、配置文件
import org.springframework.boot.web.servlet.FilterRegistrationBean;
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;import javax.servlet.DispatcherType;/*** author smalljop* description 过滤器配置* create 2019-01-29 16:27**/
Configuration
public class FilterConfig {/*** 跨域过滤器** return*/Beanpublic FilterRegistrationBean corsFilterRegistration() {FilterRegistrationBean registration new FilterRegistrationBean();registration.setDispatcherTypes(DispatcherType.REQUEST);CorsConfiguration config new CorsConfiguration();config.addAllowedOrigin(*);config.addAllowedMethod(*);config.addAllowedHeader(*);UrlBasedCorsConfigurationSource corsConfigurationSource new UrlBasedCorsConfigurationSource();corsConfigurationSource.registerCorsConfiguration(/**, config);CorsFilter corsFilter new CorsFilter(corsConfigurationSource);registration.setOrder(Integer.MAX_VALUE - 4);registration.setFilter(corsFilter);return registration;}
}4.1.2、项目
链接https://pan.baidu.com/s/1tEHpnsvAlQ6g4N4aiocp-g?pwdmulu
提取码mulu
4.1.3、结果验证
启动后端代码在浏览器访问test.html通过F12查看网络可以看到请求test1正常执行并且有返回值
4.2、SpringBootWebMvcConfigurer
4.2.1、配置文件
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 WebMvcConfig implements WebMvcConfigurer {Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping(/**).allowedOriginPatterns(*).allowCredentials(true).allowedMethods(GET, POST, PUT, DELETE, OPTIONS).maxAge(3600);}}4.2.2、项目
链接https://pan.baidu.com/s/1iaZuG1BfUZt_FaNyDyXRfQ?pwdxorq
提取码xorq
4.2.3、结果验证
启动后端代码在浏览器访问test.html通过F12查看网络可以看到请求test1正常执行并且有返回值
4.3、SpringBootCrossOrigin
4.3.1、使用示例
Api(value 测试, tags {测试}) // 必须添加tags否则UI界面中不会显示当前类的中文说明
RestController
RequestMapping(/test)
CrossOrigin
public class TestController {……
}4.3.2、项目
链接https://pan.baidu.com/s/1af-rXbnDRzia47NReUQZ_w?pwdhewt
提取码hewt
4.3.3、结果验证
4.4、SpringBootSpringSecurity 过滤器
4.4.1、配置文件
ResourcesConfig
import org.springframework.beans.factory.annotation.Autowired;
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;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.framework.interceptor.RepeatSubmitInterceptor;/*** 通用配置* * author ruoyi*/
Configuration
public class ResourcesConfig implements WebMvcConfigurer
{Autowiredprivate RepeatSubmitInterceptor repeatSubmitInterceptor;Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry){/** 本地文件上传路径 */registry.addResourceHandler(Constants.RESOURCE_PREFIX /**).addResourceLocations(file: RuoYiConfig.getProfile() /);/** swagger配置 */registry.addResourceHandler(/swagger-ui/**).addResourceLocations(classpath:/META-INF/resources/webjars/springfox-swagger-ui/);}/*** 自定义拦截规则*/Overridepublic void addInterceptors(InterceptorRegistry registry){registry.addInterceptor(repeatSubmitInterceptor).addPathPatterns(/**);}/*** 跨域配置*/Beanpublic CorsFilter corsFilter(){CorsConfiguration config new CorsConfiguration();config.setAllowCredentials(true);// 设置访问源地址config.addAllowedOriginPattern(*);// 设置访问源请求头config.addAllowedHeader(*);// 设置访问源请求方法config.addAllowedMethod(*);// 有效期 1800秒config.setMaxAge(1800L);// 添加映射路径拦截一切请求UrlBasedCorsConfigurationSource source new UrlBasedCorsConfigurationSource();source.registerCorsConfiguration(/**, config);// 返回新的CorsFilterreturn new CorsFilter(source);}
}SecurityConfig
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.web.filter.CorsFilter;
import com.ruoyi.framework.config.properties.PermitAllUrlProperties;
import com.ruoyi.framework.security.filter.JwtAuthenticationTokenFilter;
import com.ruoyi.framework.security.handle.AuthenticationEntryPointImpl;
import com.ruoyi.framework.security.handle.LogoutSuccessHandlerImpl;/*** spring security配置* * author ruoyi*/
EnableGlobalMethodSecurity(prePostEnabled true, securedEnabled true)
public class SecurityConfig extends WebSecurityConfigurerAdapter
{/*** 自定义用户认证逻辑*/Autowiredprivate UserDetailsService userDetailsService;/*** 认证失败处理类*/Autowiredprivate AuthenticationEntryPointImpl unauthorizedHandler;/*** 退出处理类*/Autowiredprivate LogoutSuccessHandlerImpl logoutSuccessHandler;/*** token认证过滤器*/Autowiredprivate JwtAuthenticationTokenFilter authenticationTokenFilter;/*** 跨域过滤器*/Autowiredprivate CorsFilter corsFilter;/*** 允许匿名访问的地址*/Autowiredprivate PermitAllUrlProperties permitAllUrl;/*** 解决 无法直接注入 AuthenticationManager** return* throws Exception*/BeanOverridepublic AuthenticationManager authenticationManagerBean() throws Exception{return super.authenticationManagerBean();}/*** anyRequest | 匹配所有请求路径* access | SpringEl表达式结果为true时可以访问* anonymous | 匿名可以访问* denyAll | 用户不能访问* fullyAuthenticated | 用户完全认证可以访问非remember-me下自动登录* hasAnyAuthority | 如果有参数参数表示权限则其中任何一个权限可以访问* hasAnyRole | 如果有参数参数表示角色则其中任何一个角色可以访问* hasAuthority | 如果有参数参数表示权限则其权限可以访问* hasIpAddress | 如果有参数参数表示IP地址如果用户IP和参数匹配则可以访问* hasRole | 如果有参数参数表示角色则其角色可以访问* permitAll | 用户可以任意访问* rememberMe | 允许通过remember-me登录的用户访问* authenticated | 用户登录后可访问*/Overrideprotected void configure(HttpSecurity httpSecurity) throws Exception{// 注解标记允许匿名访问的urlExpressionUrlAuthorizationConfigurerHttpSecurity.ExpressionInterceptUrlRegistry registry httpSecurity.authorizeRequests();permitAllUrl.getUrls().forEach(url - registry.antMatchers(url).permitAll());httpSecurity// CSRF禁用因为不使用session.csrf().disable()// 认证失败处理类.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()// 基于token所以不需要session.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()// 过滤请求.authorizeRequests()// 对于登录login 注册register 验证码captchaImage 允许匿名访问.antMatchers(/login, /register, /captchaImage).anonymous()// 静态资源可匿名访问.antMatchers(HttpMethod.GET, /, /*.html, /**/*.html, /**/*.css, /**/*.js, /profile/**).permitAll().antMatchers(/swagger-ui.html, /swagger-resources/**, /webjars/**, /*/api-docs, /druid/**).permitAll()// 除上面外的所有请求全部需要鉴权认证.anyRequest().authenticated().and().headers().frameOptions().disable();// 添加Logout filterhttpSecurity.logout().logoutUrl(/logout).logoutSuccessHandler(logoutSuccessHandler);// 添加JWT filterhttpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);// 添加CORS filterhttpSecurity.addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class);httpSecurity.addFilterBefore(corsFilter, LogoutFilter.class);}/*** 强散列哈希加密实现*/Beanpublic BCryptPasswordEncoder bCryptPasswordEncoder(){return new BCryptPasswordEncoder();}/*** 身份认证接口*/Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception{auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());}
}4.4.2、项目
RuoYi-Vue
4.5、SpringCloud-GatewayCorsWebFilter
4.5.1、配置文件
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;/*** 跨域配置* * author ruoyi*/
Configuration
public class CorsConfig
{BeanCorsWebFilter corsWebFilter() {CorsConfiguration corsConfig new CorsConfiguration();
// List list new ArrayList();
// list.add(*);
// corsConfig.setAllowedOrigins(list);corsConfig.setAllowCredentials(true);corsConfig.setMaxAge(3600L);corsConfig.addAllowedMethod(PUT);corsConfig.addAllowedMethod(DELETE);corsConfig.addAllowedMethod(GET);corsConfig.addAllowedMethod(POST);corsConfig.addAllowedMethod(OPTIONS);corsConfig.addAllowedHeader(*);corsConfig.addAllowedOriginPattern(*);corsConfig.addExposedHeader(access-control-allow-headers);corsConfig.addExposedHeader(access-control-allow-methods);corsConfig.addExposedHeader(access-control-allow-origin);corsConfig.addExposedHeader(access-control-max-age);corsConfig.addExposedHeader(X-Frame-Options);UrlBasedCorsConfigurationSource source new UrlBasedCorsConfigurationSource();source.registerCorsConfiguration(/**, corsConfig);return new CorsWebFilter(source);}
}4.5.2、项目
链接https://pan.baidu.com/s/1r6ivfYfA6Qel7uqmVU4OHg?pwdnbtj
提取码nbtj
4.5.3、结果验证
启动后端代码在浏览器访问test.html通过F12查看网络可以看到请求test1正常执行并且有返回值
4.6、SpringCloud-GatewayWebFilter
4.6.1、配置文件
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.cors.reactive.CorsUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;/*** 跨域配置* * author ruoyi*/
Configuration
public class CorsConfig
{private static final String ALLOWED_HEADERS *;private static final String ALLOWED_METHODS GET,POST,PUT,DELETE,OPTIONS,HEAD;private static final String ALLOWED_ORIGIN *;private static final String ALLOWED_EXPOSE *;private static final String MAX_AGE 18000L;Beanpublic WebFilter corsFilter(){return (ServerWebExchange ctx, WebFilterChain chain) - {ServerHttpRequest request ctx.getRequest();if (CorsUtils.isCorsRequest(request)){ServerHttpResponse response ctx.getResponse();HttpHeaders headers response.getHeaders();headers.add(Access-Control-Allow-Headers, ALLOWED_HEADERS);headers.add(Access-Control-Allow-Methods, ALLOWED_METHODS);headers.add(Access-Control-Allow-Origin, ALLOWED_ORIGIN);headers.add(Access-Control-Expose-Headers, ALLOWED_EXPOSE);headers.add(Access-Control-Max-Age, MAX_AGE);headers.add(Access-Control-Allow-Credentials, true);if (request.getMethod() HttpMethod.OPTIONS){response.setStatusCode(HttpStatus.OK);return Mono.empty();}}return chain.filter(ctx);};}
}4.6.2、项目
链接https://pan.baidu.com/s/1wn9b-ZBDED91YeTrEtWr-A?pwdq2jx
提取码q2jx
4.6.3、结果验证
启动后端代码在浏览器访问test.html通过F12查看网络可以看到请求test1正常执行并且有返回值
4.7、SpringCloud-Gatewaybootstrap.yml
4.7.1、配置文件bootstrap.yml
spring:cloud:gateway:globalcors:corsConfigurations:[/**]:allowedOriginPatterns: *allowed-methods: *allowed-headers: *allow-credentials: trueexposedHeaders: Content-Disposition,Content-Type,Cache-Control4.7.2、项目
链接https://pan.baidu.com/s/1MyWulmXILdcrdNOUmkCbJg?pwd7hgz
提取码7hgz
4.7.3、结果验证
启动后端代码在浏览器访问test.html通过F12查看网络可以看到请求test1正常执行并且有返回值