feat: JWT authentication middleware and login endpoint

This commit is contained in:
iamatulsingh
2026-03-08 21:00:28 +01:00
parent 54ce4d417f
commit b5ac108719
4 changed files with 87 additions and 2 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/../../../.." vcs="Git" />
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>
+1
View File
@@ -3,6 +3,7 @@ module whatsapp-mcp-server
go 1.25.0
require (
github.com/golang-jwt/jwt/v5 v5.2.2
github.com/mattn/go-sqlite3 v1.14.34
github.com/modelcontextprotocol/go-sdk v1.3.1
)
+77
View File
@@ -0,0 +1,77 @@
package helpers
import (
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"strings"
"sync"
"time"
"github.com/golang-jwt/jwt/v5"
)
var (
apiSecret = ReadEnv("WHATSAPP_API_SECRET", "")
jwtToken string
tokenMutex sync.Mutex
tokenExpiresAt time.Time
)
// GetOrRefreshJwtToken returns a valid JWT or fetches a new one
func GetOrRefreshJwtToken() (string, error) {
tokenMutex.Lock()
defer tokenMutex.Unlock()
// Reuse token if still valid
if jwtToken != "" && time.Now().Before(tokenExpiresAt.Add(-30*time.Second)) {
return jwtToken, nil
}
// Request new token
req, err := http.NewRequest("POST", fmt.Sprintf("%s/%s", strings.TrimSuffix(apiBaseURL, "/api"), "auth/login"), nil)
if err != nil {
return "", err
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", apiSecret))
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
return "", fmt.Errorf("auth request failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return "", fmt.Errorf("auth failed %d: %s", resp.StatusCode, string(body))
}
var data struct {
Token string `json:"token"`
}
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
return "", fmt.Errorf("failed to decode token response: %w", err)
}
if data.Token == "" {
return "", fmt.Errorf("no token returned from /auth/login")
}
// Parse WITHOUT verifying signature
parsed, _, err := jwt.NewParser().ParseUnverified(data.Token, jwt.MapClaims{})
if err == nil {
if claims, ok := parsed.Claims.(jwt.MapClaims); ok {
if exp, ok := claims["exp"].(float64); ok {
tokenExpiresAt = time.Unix(int64(exp), 0)
}
}
}
jwtToken = data.Token
slog.Info("Fetched new JWT token", "expires", tokenExpiresAt)
return jwtToken, nil
}
+8 -1
View File
@@ -179,6 +179,11 @@ type downloadMediaInput struct {
}
func callAPI(method, path string, body any) ([]byte, error) {
token, err := GetOrRefreshJwtToken()
if err != nil {
return nil, fmt.Errorf("authentication failed: %w", err)
}
var reqBody io.Reader
if body != nil {
b, err := json.Marshal(body)
@@ -188,12 +193,14 @@ func callAPI(method, path string, body any) ([]byte, error) {
reqBody = bytes.NewReader(b)
}
req, err := http.NewRequest(method, apiBaseURL+path, reqBody)
fullURL := fmt.Sprintf("%s%s", apiBaseURL, path)
req, err := http.NewRequest(method, fullURL, reqBody)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
client := &http.Client{Timeout: apiTimeout}
resp, err := client.Do(req)