【问题标题】:How to save cookies in browser using GO + REACT?如何使用 GO + REACT 在浏览器中保存 cookie?
【发布时间】:2021-04-24 23:57:16
【问题描述】:

我使用 react over Go rest-API 创建了一个登录页面,但我发现 Browser 没有保存在登录阶段建立的 cookie。我尝试了一些通过 stackoverflow 解决的类似问题,但没有一个对我有用。 -- 希望有人能帮我解决这个问题

GO - 后端

func main(){
    HandleRequests()
}

func HandleRequests(){
    r := mux.NewRouter().StrictSlash(true)
    r.HandleFunc("/login", Middleware(Login)).Methods("POST")
    handler := cors.Default().Handler(r)
    log.Fatal(http.ListenAndServe(":8081", handler))
}

func Middleware(h http.HandlerFunc) http.HandlerFunc {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")
        h.ServeHTTP(w, r)
    })

}

func Login(w http.ResponseWriter, r *http.Request) {
    /*
        Compare Both User Name && Password
        READ - BODY
        Create New JWT
     */
    cookie := &http.Cookie{
        Name:     "jwt",
        Value:    token,
        Expires:  time.Now().Add(time.Minute * 60),
        HttpOnly: true,
    }

    http.SetCookie(w, cookie)

    respondWithJson(w, http.StatusOK, struct {
        Ok string `json:"ok"`
    }{
        Ok: "Success, Welcome back our friend !",
    })
}

func respondWithJson(w http.ResponseWriter, code int, payload interface{}) {
    response, _ := json.Marshal(payload)
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(code)
    w.Write(response)
}

REACT - 路由器 - 前端 React 跑过来了,http://localhost:3000

import React, { SyntheticEvent, useState } from 'react';
import { Redirect } from 'react-router-dom';

const Login = () => {
    const[username, setUsername] = useState('');
    const[password, setPassword] = useState('');
    const[redirect, setRedirect] = useState(false)

    const submit = async (e : SyntheticEvent) => {
        e.preventDefault();
        await fetch('http://localhost:8081/login', {
            method : 'POST',
            headers: {'Content-Type':'application/json'},
            body: JSON.stringify({
                username,               
                password
            }),
            credentials:'include'
        });
        setRedirect(true);
    }
    if (redirect) {
        return <Redirect to = "/"/>;
    }
    return (
        <form onSubmit={submit}>
            <h1 className="h3 mb-3 fw-normal">Please sign in</h1>
            <input type="text" className="form-control"  placeholder="Username" required
                onChange = {e => setUsername(e.target.value)}/>
            <input type="password" className="form-control" placeholder="Password" required
                onChange = {e => setPassword(e.target.value)}/>
            <div className="checkbox mb-3">
                <label>
                    <input type="checkbox" value="remember-me" /> Remember me
                </label>
            </div>
            <button className="w-100 btn btn-lg btn-primary" type="submit">Sign in</button>
        </form>
    );
};

【问题讨论】:

  • cookie 路径默认为请求路径,/login。要访问cookie的其他路径,请将路径设置为/cookie := &amp;http.Cookie{Path: "/", ...}
  • 还是不行。

标签: reactjs go react-router mux


【解决方案1】:

浏览器无法保存 cookie,因为 HttpOnly 选项为真。 如果要将 cookie 保存到客户端浏览器,请将 HttpOnly 选项设置为 false。 但是这样防御 XSS 攻击并不安全。

cookie := &http.Cookie{
    Name:     "jwt",
    Value:    token,
    Expires:  time.Now().Add(time.Minute * 60),
    HttpOnly: false,
}

Restrict access to cookies

【讨论】:

    猜你喜欢
    • 2012-02-27
    • 2020-12-11
    • 1970-01-01
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    • 2012-01-22
    • 2016-08-10
    • 2021-02-28
    相关资源
    最近更新 更多