Golang React 授权

问题描述 投票:0回答:1

我正在使用 React 作为前端,使用 Go 作为后端。

我使用 JWT 令牌来授权用户。这是一个用于安全路由的 JWT 中间件。 问题是我使用 cookie 进行授权,中间件也会检查 cookie 进行验证。当我在 React 中使用 localStorage 来保存 JWT 时。 更准确地说,代码在这里:

http.SetCookie(w, &http.Cookie{ // on Login
    Name:     "token",
    Value:    tokenString,
    Expires:  time.Now().UTC().Add(time.Hour),
    HttpOnly: true, // Prevents client-side JS from accessing the cookie
    Secure:   true, // Ensures cookie is sent over HTTPS
    Path:     "/",  // Cookie available to entire domain
})

http.SetCookie(w, &http.Cookie{ // on Logout
    Name:     "token",
    Value:    "",
    Expires:  time.Unix(0, 0),
    HttpOnly: true,
    Secure:   true,
    Path:     "/",
})

这是中间件:

func JWTMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    c, err := r.Cookie("token")
    if err != nil {
        if err == http.ErrNoCookie {
            functionalities.WriteJSON(w, http.StatusUnauthorized, APIServerError{Error: "Unauthorized"})
            return
        }
        functionalities.WriteJSON(w, http.StatusBadRequest, APIServerError{Error: err.Error()})
        return
    }


    tknStr := c.Value
    claims := &Claims{}

    tkn, err := jwt.ParseWithClaims(tknStr, claims, func(token *jwt.Token) (interface{}, error) {
        if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
            return nil, http.ErrNotSupported
        }

        return []byte("SECRET"), nil
    })

    if err != nil {
        if err == jwt.ErrSignatureInvalid {
            functionalities.WriteJSON(w, http.StatusUnauthorized, APIServerError{Error: "Unauthorized"})
            return
        }
        functionalities.WriteJSON(w, http.StatusBadRequest, APIServerError{Error: err.Error()})
        return
    }
    if !tkn.Valid {
        functionalities.WriteJSON(w, http.StatusUnauthorized, APIServerError{Error: "Unauthorized"})
        return
    }

    next.ServeHTTP(w, r)
})

}

正如我在前端使用 localStorage 之前所写的。

所以我不知道如何发送这样的请求:

useEffect (() => {
const userId = 'your_user_id_here'; // Replace this with actual logic to retrieve the user's ID
const fetchProfile = async () => {
  try {
    const response = await axios.get(`http://127.0.0.1:8080/api/accounts/${userId}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('authToken')}` // Assuming the token is stored in local storage
      }
    });

    // Assuming the response data structure matches the expected profile data
    setProfileData(response.data);
  } catch (error) {
    console.error('Profile fetch error:', error.response ? error.response.data : error.message);
  }
};

fetchProfile();

}, []);

伙计们,如果你们帮助我或指导我解决这个问题,我会非常高兴。我准备重写后端并做更激进的事情:D

reactjs go jwt authorization
1个回答
0
投票

授权标头现在直接从

cookie
而不是从本地存储读取令牌。

document.cookie
属性用于访问cookie。正则表达式用于提取令牌cookie的值。


useEffect(() => {
  const fetchProfile = async () => {
    try {
      const response = await axios.get(`http://127.0.0.1:8080/api/accounts/${userId}`, {
        // No need to read from local storage, read from cookie instead
        headers: {
          'Authorization': `Bearer ${document.cookie.replace(/(?:(?:^|.*;\s*)token\s*\=\s*([^;]*).*$)|^.*$/, "$1")}`
        }
      });

      // Assuming the response data structure matches the expected profile data
      setProfileData(response.data);
    } catch (error) {
      console.error('Profile fetch error:', error.response ? error.response.data : error.message);
    }
  };

  fetchProfile();
}, []);

假设饼干在那里。

© www.soinside.com 2019 - 2024. All rights reserved.