服务端SpringBoot2.x :localhost:8082
前端Vue2.x :localhost:81
前后端的端口号不同,为跨域,导致前端访问后端时,每次访问都新生产一个sessionID。解决如下:
后端:
1.添加过滤器:
- package com.nsoft.gkzp.syscore.config.filter;
- import org.apache.logging.log4j.LogManager;
- import org.apache.logging.log4j.Logger;
- import org.springframework.web.bind.annotation.RequestMethod;
- import javax.servlet.*;
- import javax.servlet.annotation.WebFilter;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.io.IOException;
- @WebFilter(urlPatterns = "/*", filterName = "corsFilter")
- public class CorsFilter implements Filter {
- final private static Logger logger = LogManager.getLogger(CorsFilter.class);
- @Override
- public void destroy() {
- }
- /**
- * 此过滤器只是处理跨域问题
- * @param servletRequest
- * @param servletResponse
- * @param chain
- * @throws ServletException
- * @throws IOException
- */
- @Override
- public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException {
- HttpServletRequest request = (HttpServletRequest) servletRequest;
- HttpServletResponse response = (HttpServletResponse) servletResponse;
- String origin = request.getHeader("Origin");
- if(origin == null) {
- origin = request.getHeader("Referer");
- }
- response.setHeader("Access-Control-Allow-Origin", origin);// 允许指定域访问跨域资源(这里不能写*,*代表接受所有域名访问,如写*则下面一行代码无效。谨记)
- response.setHeader("Access-Control-Allow-Credentials", "true");//true代表允许客户端携带cookie(此时origin值不能为“*”,只能为指定单一域名)
- response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH"); /// 允许浏览器在预检请求成功之后发送的实际请求方法名
- response.setHeader("Access-Control-Allow-Headers", "Authorization,Origin, X-Requested-With, Content-Type, Accept,Access-Token");// 允许浏览器发送的请求消息头
- //response.setHeader("Access-Control-Max-Age", "86400"); // 浏览器缓存预检请求结果时间,单位:秒
- chain.doFilter(request,response);
- }
- @Override
- public void init(FilterConfig filterConfig) throws ServletException {
- }
- }
2. springboot2.配置过滤器时,启动类必须加上@ServletComponentScan才会加载过滤器
- package com.nsoft.gkzp;
- import org.mybatis.spring.annotation.MapperScan;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.boot.web.server.ConfigurableWebServerFactory;
- import org.springframework.boot.web.server.ErrorPage;
- import org.springframework.boot.web.server.WebServerFactoryCustomizer;
- import org.springframework.boot.web.servlet.ServletComponentScan;
- import org.springframework.context.annotation.Bean;
- import org.springframework.http.HttpStatus;
- import org.springframework.web.servlet.config.annotation.CorsRegistry;
- import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
- import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
- /**
- * springboot入口
- * MapperScan("com.nsoft.gkzp.**.dao")为扫描mapper, 所以dao下面的类就不需要添加@mapper注解了
- * ServletComponentScan 添加了过滤器,故这里要添加@ServletComponentScan注解,spring才会扫描到过滤器(eg:com.nsoft.gkzp.syscore.config.filter.CorsFilter)
- */
- @SpringBootApplication
- @ServletComponentScan
- @MapperScan("com.nsoft.gkzp.**.dao")
- public class GzyGkzpApplication {
- public static void main(String[] args) {
- SpringApplication.run(GzyGkzpApplication.class, args);
- }
- /**
- * 在springboot整合vue前端时,vue使用url跳转时报404错误,此处代码解决此问题
- * 参照https://blog.csdn.net/Mr_EvanChen/article/details/83625082
- */
- @Bean
- public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer(){
- return factory -> {
- ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/index.html");
- factory.addErrorPages(error404Page);
- };
- }
- }
3. spring-session 2.x
中 Cookie
里面了SameSite
,他默认值是 Lax
SameSite Cookie 是用来防止CSRF攻击,它有两个值:Strict、Lax
SameSite = Strict:意为严格模式,表明这个cookie在任何情况下都不可能作为第三方cookie;
SameSite = Lax :意为宽松模式,在get请求是可以作为第三方cookie,但是不能携带cookie进行跨域post访问(这就很蛋疼了,我们那个校验接口就是POST请求)
- package com.nsoft.gkzp.syscore.config;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.session.web.http.CookieSerializer;
- import org.springframework.session.web.http.DefaultCookieSerializer;
- /**
* https://www.cnblogs.com/hujinshui/p/11025848.html
* spring-session 2.x 中 Cookie里面引入了SameSite他默认值是 Lax,
* SameSite Cookie 是用来防止CSRF攻击,它有两个值:Strict、Lax
* SameSite = Strict:意为严格模式,表明这个cookie在任何情况下都不可能作为第三方cookie;
* SameSite = Lax:意为宽松模式,在get请求是可以作为第三方cookie,但是不能携带cookie进行跨域post访问
* 总结:前端请求到后台,每次session都不一样,每次都是新的会话,导致获取不到用户信息
*/
- @Configuration public class SpringSessionConfig { public SpringSessionConfig() { } @Bean public CookieSerializer httpSessionIdResolver() { DefaultCookieSerializer cookieSerializer = new DefaultCookieSerializer(); // 取消仅限同一站点设置 cookieSerializer.setSameSite(null); return cookieSerializer; } }
前端:
1.在 main.js (前端用axios)
- import axios from 'axios';
- axios.defaults.withCredentials=true;//让ajax携带cookie
用了1天半时间,改了很多次依然不行,后来发现是前端用了 proxy 代理,它本身也是已经处理了跨域问题,网上找的时候发现有的文章也用到这个了。但我这里就是不行。
我原来的代码:
1)写的注册页面:

2)全局配置如下:
main.js
- // xenv 标记当前环境 true:开发环境 false:生产环境
- const xenv = true;
- // 注册全局变量
- Vue.prototype.$global = {
- //contentPath 标记根路径,主要用于axios请求后端数据的url
- contentPath: xenv ? '/api/' : router.options.base
- };
(xenv设为true;所以 根路径contentPath的值必为‘/api/’ ,而‘/api/’ 在vue.config.js里配置为代理,如下。)
vue.config.js
- devServer: {
- open: true,
- host: '0.0.0.0',
- port: 80,
- https: false,
- hotOnly: false,
- before: app => {
- },
- proxy: {
- // 配置跨域
- '/api': {
- target: 'http://127.0.0.1:8082/',
- ws: true,
- changOrigin: true,
- pathRewrite: {
- '^/api': '/'
- }
- }
- }
- },
2.不使用proxy代理,把根目录写死为'http://127.0.0.1:8082/',就成功了,修改如下:
main.js:
- // xenv 标记当前环境 true:开发环境 false:生产环境
- const xenv = true;
- // 注册全局变量
- Vue.prototype.$global = {
- // contentPath 标记根路径,主要用于axios请求后端数据的url
- // contentPath: xenv ? '/api/' : router.options.base
- contentPath: 'http://127.0.0.1:8082/'
- };
另:为了安全起见,可在服务端设置可跨域访问的白名单地址,参照 https://blog.csdn.net/qq_15054679/article/details/90684703
参照:
https://www.cnblogs.com/zimublog/p/10786110.html
https://blog.csdn.net/qq_17555933/article/details/92017890