后端设置 Session 前端无法正确获取问题如何解决?

335 天前
 tiRolin

我同学用鱼皮的后端内容做一个简单的课设,前端是他自己写的,后端基本没动,后端使用 JDK18

登录时进行账号密码的验证之后会记录用户的登录态,其代码是下面这行

request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, user);

调用对应的方法是

Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
User currentUser = (User) userObj;
//如果未登录,抛出异常
if (currentUser == null || currentUser.getId() == null) {
   throw new GlobalException(new Result<>().error(BusinessFailCode.IS_NOT_LOGIN));
}

按说是一切正常的,但是问题是前端往后端执行增删改的方法时,就一定会查找不到对应的用户,后端在 Swagger 中测试是一切正常的,但是前端就不行

查看了内容之后发现后端在登录时有返回对应的登录用 Session 数据,但是前端总是得不到结果,在 Cookie 中找不到相关数据

我猜测这可能和跨域问题有关,但是我看了后端,已经设置过 CORS 了,配置如下

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 覆盖所有请求
        registry.addMapping("/**")
                // 允许发送 Cookie
                .allowCredentials(true)
                // 放行哪些域名(必须用 patterns ,否则 * 会和 allowCredentials 冲突)
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .exposedHeaders("*");
    }
}

现在我就是,搞不懂这个问题如何解决,我真的没办法了所以来问问,希望大佬救一下

1548 次点击
所在节点    Java
7 条回复
wangsongyan
335 天前
你处理跨域代码里面的注释都不看的吗?
siweipancc
335 天前
你们前后端都上 mdn 看一下 cookie 定义,浏览器 f12 打开,看一下 cookies 存储器在不同环境的创建
siweipancc
335 天前
还有楼上说的,看一下 CorsConfiguration 469 行
superedlimited
335 天前
这个鱼皮,代码写得不行啊,这波推广做的不行啊。
Oktfolio
334 天前
The Domain and Path attributes define the scope of the cookie. They essentially tell the browser what website the cookie belongs to. For security reasons, cookies can only be set on the current resource's top domain and its subdomains, and not for another domain and its subdomains. For example, the website example.org cannot set a cookie that has a domain of foo.com because this would allow the website example.org to control the cookies of the domain foo.com.
tiRolin
334 天前
@siweipancc 不好意思,能麻烦大佬再说得详细一点吗?我听不太懂就是,我查了下 mdn 好似是前端内容,但我是写后端的,我现在就是帮我朋友解决这个问题就是
能麻烦您再讲详细一点吗?不胜感激
tiRolin
334 天前
@wangsongyan 能具体说一下 CorsConfig 里哪里做错了吗?我光看注释我没理解我哪里做错了就是,因为我水平比较低,所以整不太明白,见谅

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/947736

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX