使用axious发送登录请求时发现响应返回Set-Cookie一直不成功,浏览器错误提示如下:
看了一些文章说是因为浏览器考虑安全问题导致的,相关内容就不介绍了,这里主要介绍我使用的有效的方法,简单一步。 只需创建config文件夹并新建SessionConfig类:
import org.springframework.boot.autoconfigure.session.DefaultCookieSerializerCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.MapSessionRepository;
import org.springframework.session.SessionRepository;
import org.springframework.session.config.annotation.web.http.EnableSpringHttpSession;
import org.springframework.session.web.http.DefaultCookieSerializer;
import java.util.concurrent.ConcurrentHashMap;
@Configuration
@EnableSpringHttpSession
public class SessionConfig {
@Bean
public SessionRepository sessionRepository() {
return new MapSessionRepository(new ConcurrentHashMap<>());
}
@Bean
DefaultCookieSerializerCustomizer cookieSerializerCustomizer() {
return new DefaultCookieSerializerCustomizer() {
@Override
public void customize(DefaultCookieSerializer cookieSerializer) {
cookieSerializer.setSameSite("None");
cookieSerializer.setUseSecureCookie(true); // 此项必须,否则set-cookie会被chrome浏览器阻拦
}
};
}
}
再次去浏览器检查就能发现可以后端发来的Cookie可以被前端正常保存了
记得在application.xml里配置以下代码,作用是让这个Cookie只能在本地域名使用
session:
cookie:
domain: localhost
这样后端传来的Cookie可以在前端正常保存,但当前端向后端请求时携带Cookie也需要设置一下 只需在myAxios.ts(你的Axios文件)里添加以下片段即可:
myAxios.defaults.withCredentials = true; // 配置为true
本人小白,很多表达可能不准确,还请指正