登录
首页 >  Golang >  Go问答

浏览器未在本地主机设置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

客户端来源

我使用它作为发送和接收数据的测试表单。



Please Login

Just a basic login 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学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>