auth.go 892 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package middleware
  2. import (
  3. "fmt"
  4. "net/http"
  5. "github.com/lf-edge/ekuiper/internal/pkg/jwt"
  6. )
  7. var notAuth = []string{"/", "/ping"}
  8. var Auth = func(next http.Handler) http.Handler {
  9. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  10. requestPath := r.URL.Path
  11. for _, value := range notAuth {
  12. if value == requestPath {
  13. next.ServeHTTP(w, r)
  14. return
  15. }
  16. }
  17. tokenHeader := r.Header.Get("Authorization")
  18. if tokenHeader == "" {
  19. http.Error(w, "missing_token", http.StatusUnauthorized)
  20. return
  21. }
  22. tk, err := jwt.ParseToken(tokenHeader)
  23. if err != nil {
  24. http.Error(w, err.Error(), http.StatusUnauthorized)
  25. return
  26. }
  27. if tk.StandardClaims.Audience != "eKuiper" {
  28. http.Error(w, fmt.Sprintf("audience field should be eKuiper, but got %s", tk.StandardClaims.Audience), http.StatusUnauthorized)
  29. return
  30. }
  31. next.ServeHTTP(w, r)
  32. })
  33. }