简体   繁体   English

未保存在移动设备上的 Cookie

[英]Cookies not saved on mobile

I'm using next middleware to do protected routes and I'm using cookies to do the checking since you can use cookies on the server-side.我正在使用下一个中间件来执行受保护的路由,并且我正在使用 cookie 进行检查,因为您可以在服务器端使用 cookie。

When a user logged in, I save the info on local storage(for all my frontend auth checks) and a cookie set to true if logged in(for server-side checking).当用户登录时,我将信息保存在本地存储中(用于我的所有前端身份验证检查),如果登录则将 cookie 设置为true (用于服务器端检查)。

The issue is that when im on mobile, and a user logs in, the info is saved successfully.问题是当我在移动设备上并且用户登录时,信息已成功保存。 But if the user closes the browser(like safari) then opens it again and goes to the site, the user is still logged in but the Cookie doesnt seem to work(or is no longer there) but the localstorage still is there.但是,如果用户关闭浏览器(如 safari)然后再次打开它并转到该站点,用户仍然登录但 Cookie 似乎不起作用(或不再存在)但本地存储仍然存在。 Then this causes a case where the user is logged in but they cant access the logged in(protected) routes.然后这会导致用户登录但他们无法访问登录的(受保护的)路由的情况。

The following is my login in function以下是我的登录功能

    let loginUser = async (e) => {
        e.preventDefault();
        let response = await fetch(URL, {
            method:'POST',
            headers:{
                'Content-Type': 'application/json'
            },
            body:JSON.stringify({'email':e.target.email.value, 'password':e.target.password.value})
        })
        if(response.ok){
            let data = await response.json();
            setAuthTokens(data);
            localStorage.setItem("authTokens", JSON.stringify(data));
            Cookies.set("auth", "true");
            setUser(true);
            setFailed(false);
            router.push("/dashboard");
        } else {
            setFailed(true)
        }
    }

The following is my middleware以下是我的中间件

export default function middleware(req, event) {
    let verify = req.cookies['auth']
    const url = req.url

    if (url.includes("/login") || url.includes("/signup")) {
      if (verify) {
        return NextResponse.redirect("some_url/dashboard");
      }
    }

    if (url == "some_url" && verify) {
      return NextResponse.redirect("some_url/dashboard");
    }

    if(url.includes("/dashboard")){
        if(!verify){
            return NextResponse.redirect("some_url/login");
        }
    }
}

This code may cause some security issues so I suggest you to set cookie from server also have an API for logout that clears cookie.此代码可能会导致一些安全问题,因此我建议您从服务器设置 cookie 还有一个用于清除 cookie 的注销 API。
BTW if you don't set expire date in your cookie safari mobile will remove it.顺便说一句,如果您没有在 cookie safari mobile 中设置过期日期,则会将其删除。 You can do this by passing options to third argument of Cookies.set() .您可以通过将选项传递给 Cookies.set() 的第三个参数来做到这一点。
It would be something like this:它会是这样的:

Cookies.set('auth', 'true', { expires: 7 }); //expires 7 days from now

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM