setup auth jwt to rather give response not redirect.

This commit is contained in:
2026-04-29 08:15:09 +02:00
parent f7ae5a786f
commit 1811648e72
2 changed files with 48 additions and 33 deletions
+29 -8
View File
@@ -2,6 +2,7 @@ package web
import (
"context"
"encoding/json"
"fmt"
"net/http"
@@ -14,21 +15,37 @@ const userIDKey contextKey = "userID"
func (s *Server) hasAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("nfeeder_token")
if err != nil {
http.Redirect(w, r, "/login", http.StatusSeeOther)
var tokenString string
// Authorization Header Bearer token
authHeader := r.Header.Get("Authorization")
if len(authHeader) > 7 && authHeader[:7] == "Bearer " {
tokenString = authHeader[7:]
}
// Fallback to Cookie (future Web Frontend)
if tokenString == "" {
if cookie, err := r.Cookie("nfeeder_token"); err == nil {
tokenString = cookie.Value
}
}
if tokenString == "" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(map[string]string{"error": "unauthorized"})
return
}
// parse and validate
claims := &jwt.RegisteredClaims{}
token, err := jwt.ParseWithClaims(cookie.Value, claims, func(t *jwt.Token) (interface{}, error) {
// check alg
token, err := jwt.ParseWithClaims(tokenString, claims, func(t *jwt.Token) (interface{}, error) {
// check/confirm alg
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
}
return jwtKey, nil
return s.jwtSecret, nil
})
/// golang-jwt the library internally runs a Valid():
@@ -36,13 +53,17 @@ func (s *Server) hasAuth(next http.Handler) http.Handler {
/// Not Before Check: It checks if the nbf (Not Before) time has passed.
/// Issued At Check: It ensures the iat isn't in the future.
if err != nil || !token.Valid {
http.Redirect(w, r, "/login", http.StatusSeeOther)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(map[string]string{"error": "invalid or expired token"})
return
}
// Verify issuer
if claims.Issuer != ISSUER {
http.Redirect(w, r, "/login", http.StatusSeeOther)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(map[string]string{"error": "invalid issuer"})
return
}