大家好,我是一名初学者开发人员,仍在学习刷新和 accessTokens,我目前正在使用 React + Golang 开发一个应用程序进行生产。
该应用程序只能由我创建的管理员访问,因此它不会公开,并且数据库需要安全,因为它包含敏感信息(订单和客户信息)。
登录后,我生成一个 JWT accessToken 并将其设置为“HttpOnly”以确保安全措施。
但是,我对如何从 cookie 访问令牌值然后将其包含在我的 API 请求中感到困惑。
[反应 VITE JSX] 获取请求示例:
fetch('http://localhost:8080/orders', {
headers: {
Authorization : 'Bearer ' //*Here im supposed to send the accessToken*,
'Content-type': 'application/json'
},
credentials: 'include',
})
.then(response => {
if (!response.ok) {
throw new Error('Failed to fetch orders');
}
return response.json();
})
[戈朗] 我的中间件函数用于验证 JWT accessToken :
// Middleware function to verify JWT token
func authMiddleware(secret []byte) mux.MiddlewareFunc {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Extract the JWT token from the Authorization header
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
http.Error(w, "Missing Authorization header", http.StatusUnauthorized)
return
}
tokenString := strings.Replace(authHeader, "Bearer ", "", 1)
// Parse and validate the token
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return secret, nil
})
if err != nil {
var authError *jwt.ValidationError
if errors.As(err, &authError) {
switch authError.Errors {
case jwt.ValidationErrorMalformed:
http.Error(w, "Malformed token", http.StatusUnauthorized)
case jwt.ValidationErrorExpired:
http.Error(w, "Token is expired", http.StatusUnauthorized)
default:
http.Error(w, "Invalid token", http.StatusUnauthorized)
}
} else {
// Handle other errors
fmt.Println("Error parsing token:", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
return
}
if !token.Valid {
http.Error(w, "Invalid token", http.StatusUnauthorized)
return
}
// Token is valid, proceed to the next handler
next.ServeHTTP(w, r)
})
}
}
有哪些可能的方法,我应该将 accessToken 存储在会话存储中吗?任何信息都可以帮助我更好地保护我的应用程序,我对身份验证过程感到非常困惑。
谢谢!
我正在尝试观看教程并学习验证和保护 accessToken 的最佳方法,因为有人可能会使用它来使用我的 API 端点来扰乱我的数据库..
在观看使用
credentials: 'include'
的教程后,我尝试了这种方法,如果我更改 authMiddleware 逻辑,它会起作用,但对我来说并不安全,我在标头请求中提取 Cookie 并验证其中发送的 JWT 令牌,而不是检查授权标头:
package main
import (
"fmt"
"net/http"
"strings"
"github.com/dgrijalva/jwt-go"
"github.com/gorilla/mux"
)
// Middleware function to verify JWT token
func authMiddleware(secret []byte) mux.MiddlewareFunc {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Extract the JWT token from the Authorization header
authHeader := r.Header.Get("Authorization")
authCookie := r.Header.Get("Cookie")
if authHeader == "" {
http.Error(w, "No Authorization", http.StatusUnauthorized)
return
}
tokenString := strings.Replace(authCookie, "gmtX=", "", 1)
fmt.Println(tokenString)
// Parse and validate the token
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return secret, nil
})
if err != nil {
fmt.Println("Error parsing token:", err)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
if !token.Valid {
fmt.Println("Token is not valid")
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// Token is valid, proceed to the next handler
next.ServeHTTP(w, r)
})
}
}
将令牌存储在会话存储中是可以接受的,因为它是短暂的。为了增强安全性,请考虑使用存储在仅 HTTP cookie 和数据库中的长期刷新令牌来刷新它。