edge-connect-mcp/auth.go

41 lines
962 B
Go

package main
import (
"crypto/subtle"
"net/http"
"strings"
)
// authenticateRequest validates the Bearer token in the request
// Implements simple Bearer token authentication for remote MCP server
// For production use, consider implementing OAuth 2.1 with PKCE
func authenticateRequest(r *http.Request, cfg *Config) bool {
// Check if authentication is required
if !cfg.RemoteAuthRequired {
return true
}
// Get Authorization header
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
return false
}
// Check Bearer token format
parts := strings.SplitN(authHeader, " ", 2)
if len(parts) != 2 || parts[0] != "Bearer" {
return false
}
token := parts[1]
// Validate token against configured tokens
for _, validToken := range cfg.RemoteAuthTokens {
// Use constant-time comparison to prevent timing attacks
if subtle.ConstantTimeCompare([]byte(token), []byte(validToken)) == 1 {
return true
}
}
return false
}