浏览器未在本地主机设置HTTPOnly Cookie
来源:stackoverflow
时间:2024-02-17 12:54:24 160浏览 收藏
欢迎各位小伙伴来到golang学习网,相聚于此都是缘哈哈哈!今天我给大家带来《浏览器未在本地主机设置HTTPOnly Cookie》,这篇文章主要讲到等等知识,如果你对Golang相关的知识非常感兴趣或者正在自学,都可以关注我,我会持续更新相关文章!当然,有什么建议也欢迎在评论留言提出!一起学习!
问题
我有一个带有登录端点的 rest api。登录端点接受用户名和密码,服务器通过发送包含一些有效负载(如 jwt)的 httponly cookie 进行响应。
我一直使用的方法已经工作了几年,直到 set-cookie
标头大约上周停止工作。在 rest api 失去功能之前,我没有接触过它的源代码,因为我当时正在开发基于 svelte 的前端。
我怀疑这与 secure
属性设置为 false
有关,因为它在本地主机中。但是,根据使用 http cookie,只要是本地主机,不安全的连接就应该没问题。我以这种方式开发 rest api 一段时间了,很惊讶地发现 cookie 不再被设置。
使用 postman 测试 api 会产生设置 cookie 的预期结果。
使用的方法
我尝试重新创建真实 api 的一般流程,并将其精简为核心要素。
package main import ( "fmt" "io/ioutil" "log" "net/http" "os" "os/signal" "syscall" "time" "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/cors" "github.com/golang-jwt/jwt/v4" ) const idletimeout = 5 * time.second func main() { app := fiber.new(fiber.config{ idletimeout: idletimeout, }) app.use(cors.new(cors.config{ alloworigins: "*", allowheaders: "origin, content-type, accept, range", allowcredentials: true, allowmethods: "get,post,head,delete,put", exposeheaders: "x-total-count, content-range", })) app.get("/", hello) app.post("/login", login) go func() { if err := app.listen("0.0.0.0:8080"); err != nil { log.panic(err) } }() c := make(chan os.signal, 1) signal.notify(c, os.interrupt, syscall.sigterm) _ = <-c fmt.println("\n\nshutting down server...") _ = app.shutdown() } func hello(c *fiber.ctx) error { return c.sendstring("hello, world!") } func login(c *fiber.ctx) error { type logininput struct { email string `json:"email"` } var input logininput if err := c.bodyparser(&input); err != nil { return c.status(400).sendstring(err.error()) } stringurl := fmt.sprintf("https://jsonplaceholder.typicode.com/users?email=%s", input.email) resp, err := http.get(stringurl) if err != nil { return c.status(500).sendstring(err.error()) } body, err := ioutil.readall(resp.body) if err != nil { return c.status(500).sendstring(err.error()) } if len(body) > 0 { fmt.println(string(body)) } else { return c.status(400).json(fiber.map{ "message": "yeah, we couldn't find that user", }) } token := jwt.new(jwt.signingmethodhs256) cookie := new(fiber.cookie) claims := token.claims.(jwt.mapclaims) claims["purpose"] = "just a test really" signedtoken, err := token.signedstring([]byte("nicesecret")) if err != nil { // internal server error if anything goes wrong in getting the signed token fmt.println(err) return c.sendstatus(500) } cookie.name = "access" cookie.httponly = true cookie.secure = false cookie.domain = "localhost" cookie.samesite = "lax" cookie.path = "/" cookie.value = signedtoken cookie.expires = time.now().add(time.hour * 24) c.cookie(cookie) return c.status(200).json(fiber.map{ "message": "you have logged in", }) }
这基本上是通过 json 占位符的用户进行查找,如果找到具有匹配电子邮件地址的用户,则会发送 httponly cookie 并附加一些数据。
考虑到这可能是我使用的库的问题,我决定用 express 编写一个 node 版本。
import axios from 'axios' import express from 'express' import cookieparser from 'cookie-parser' import jwt from 'jsonwebtoken' const app = express() app.use(express.json()) app.use(cookieparser()) app.use(express.urlencoded({ extended: true })) app.disable('x-powered-by') app.get("/", (req, res) => { res.send("hello there!") }) app.post("/login", async (req, res, next) => { try { const { email } = req.body const { data } = await axios.get(`https://jsonplaceholder.typicode.com/users?email=${email}`) if (data) { if (data.length > 0) { res.locals.user = data[0] next() } else { return res.status(404).json({ message: "no results found" }) } } } catch (error) { return console.error(error) } }, async (req, res) => { try { let { user } = res.locals const token = jwt.sign({ user: user.name }, "mega ultra secret sauce 123") res .cookie( 'access', token, { httponly: true, secure: false, maxage: 3600 } ) .status(200) .json({ message: "you have logged in, check your cookies" }) } catch (error) { return console.error(error) } }) app.listen(8000, () => console.log(`server is up at localhost:8000`))
这两个方法都不适用于我测试过的浏览器。
结果
go 对此进行响应。
http/1.1 200 ok date: mon, 21 feb 2022 05:17:36 gmt content-type: application/json content-length: 32 vary: origin access-control-allow-origin: http://localhost:3000 access-control-allow-credentials: true access-control-expose-headers: x-total-count,content-range set-cookie: access=eyjhbgcioijiuzi1niisinr5cci6ikpxvcj9.eyjwdxjwb3nlijoisnvzdcbhihrlc3qgcmvhbgx5in0.8ykepcvnmrep1guoe_s3s7uyngslfd9rrd4jto-6upi; expires=tue, 22 feb 2022 05:17:36 gmt; domain=localhost; path=/; httponly; samesite=lax
对于 node api,这是响应标头。
http/1.1 200 ok set-cookie: access=eyjhbgcioijiuzi1niisinr5cci6ikpxvcj9.eyj1c2vyijoitgvhbm5liedyywhhbsisimlhdci6mty0ntqymdm4n30.z1nqcym5xn-l6bge_ecsmgfdcgxji2eny9sg8gcnhiu; max-age=3; path=/; expires=mon, 21 feb 2022 05:13:11 gmt; httponly content-type: application/json; charset=utf-8 content-length: 52 etag: w/"34-tsgokra49turdloqst5gb2h3nxw" date: mon, 21 feb 2022 05:13:07 gmt connection: keep-alive keep-alive: timeout=5
客户端来源
我使用它作为发送和接收数据的测试表单。
<script> let email = ""; async function handleSubmit() { try { let response = await fetch(`http://localhost:8000/login`, { method: "POST", body: JSON.stringify({ email, }), headers: { "Content-Type": "application/json", }, }); if (response) { console.info(response); let result = await response.json(); if (result) { console.info(result); } } } catch (error) { alert("Something went wrong. Check your console."); return console.error(error); } } </script> <h1>Please Login</h1> <svelte:head> <title>Just a basic login form</title> </svelte:head> <form on:submit|preventDefault={handleSubmit}> <label for="email">Email:</label> <input type="email" name="email" bind:value={email} placeholder="enter your email" /> </form>
其他信息
邮差:9.8.3
语言版本
转到:1.17.6
node.js: v16.13.1
苗条:3.44.0
使用的浏览器
mozilla firefox: 97.0.1
microsoft edge:98.0.1108.56
铬: 99.0.4781.0
正确答案
解决方案
事实证明问题出在前端,特别是 javascript 的 fetch()
方法。
let response = await fetch(`http://localhost:8000/login`, { method: "POST", credentials: "include", //--> send/receive cookies body: JSON.stringify({ email, }), headers: { "Content-Type": "application/json", }, });
您需要 credentials: 在
requestinit
对象中包含 redentials: include
属性,不仅用于发出需要 cookie 身份验证的请求,还用于接收所述 cookie。
axios 通常会自动填写这部分(根据经验),但如果没有,您还需要将 withcredentials: true
放在请求的第三个 config
参数上,以允许浏览器设置 cookie。
以上就是《浏览器未在本地主机设置HTTPOnly Cookie》的详细内容,更多关于的资料请关注golang学习网公众号!
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
139 收藏
-
204 收藏
-
325 收藏
-
478 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 514次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 499次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 484次学习