Açıklama Yok
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

auth_middleware.go 934B

12345678910111213141516171819202122232425262728293031
  1. package auth
  2. import (
  3. "context"
  4. "net/http"
  5. )
  6. // authMiddleware 验证 Authorization 头和项目 ID 头
  7. func AuthMiddleware(next http.Handler, authToken, projectIDHeader string) http.Handler {
  8. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  9. // 验证 Authorization 头
  10. authHeader := r.Header.Get("Authorization")
  11. if authHeader == "" {
  12. http.Error(w, "Authorization header required", http.StatusUnauthorized)
  13. return
  14. }
  15. expected := "Bearer " + authToken
  16. if authHeader != expected {
  17. http.Error(w, "Invalid authorization token", http.StatusUnauthorized)
  18. return
  19. }
  20. // 提取项目 ID 头并存储到请求上下文中,供 extractRequestContext 使用
  21. projectID := r.Header.Get(projectIDHeader)
  22. if projectID != "" {
  23. // 将项目 ID 存储到上下文中
  24. ctx := context.WithValue(r.Context(), "projectID", projectID)
  25. r = r.WithContext(ctx)
  26. }
  27. next.ServeHTTP(w, r)
  28. })
  29. }