How REST API Authentication and Authorization Work in AgentsView
AgentsView protects its REST endpoints using a lightweight bearer-token middleware that validates shared secrets against configuration, granting binary access to protected routes while allowing CORS pre-flight and remote-sync requests to bypass checks when configured.
AgentsView implements a straightforward security model for its HTTP server using a shared secret authentication scheme. The logic is centralized in internal/server/auth.go, where the authMiddleware function intercepts requests to validate credentials before they reach business logic handlers. This design provides a binary authorization model where possession of the configured token grants full API access, managed dynamically through the settings endpoints.
Protected Routes and Path Matching
The server distinguishes between public static assets and protected API endpoints using the protectedPath helper. Only requests targeting paths beginning with /api/ (plus profiling endpoints when enabled) trigger authentication checks.
In internal/server/auth.go, the middleware applies this filter:
// Protected paths start with /api/
if !s.protectedPath(r.URL.Path) {
next.ServeHTTP(w, r)
return
}
All other assets are served without authentication gates.
Configuration and Middleware Setup
Authentication behavior is controlled by two configuration values defined in the server configuration: cfg.AuthToken (the shared secret) and cfg.RequireAuth (a boolean flag). These values are loaded at startup from CLI flags, environment variables, or config files in cmd/agentsview/main.go.
The authMiddleware acquires a read-lock on the configuration to safely check these values:
s.cfgMu.RLock()
token := s.cfg.AuthToken
requireAuth := s.cfg.RequireAuth
s.cfgMu.RUnlock()
When requireAuth is false, the middleware skips token validation for most routes (except remote-sync paths, which still require identification).
Token Validation: Headers and Query Parameters
For standard HTTP requests, the middleware extracts the token from the Authorization: Bearer <token> header. However, for Server-Sent Events (SSE) endpoints such as /watch and /api/v1/events, the middleware also accepts a ?token= query parameter because browsers cannot set custom headers on EventSource connections.
The extraction logic in internal/server/auth.go (lines 29-44) handles both mechanisms:
// Check Authorization header first
authHeader := r.Header.Get("Authorization")
if strings.HasPrefix(authHeader, "Bearer ") {
providedToken = strings.TrimPrefix(authHeader, "Bearer ")
}
// Fallback to query parameter for SSE endpoints
if providedToken == "" {
providedToken = r.URL.Query().Get("token")
}
Special Handling for CORS and Remote Sync
The middleware includes specific logic for cross-origin resource sharing (CORS) scenarios. OPTIONS pre-flight requests are allowed to pass through immediately. When authentication is required and a token is configured, these requests are marked as authenticated so that subsequent CORS middleware permits the pre-flight to complete.
Remote-sync endpoints (/api/v1/remote-sync/) receive special treatment via the isRemoteSyncPath helper. Even when requireAuth is disabled globally, these routes require token validation to establish the "remote" authentication context, allowing machine-to-machine synchronization without exposing the entire API to unauthenticated calls.
Authorization Model and Context Propagation
AgentsView employs a binary authorization scheme rather than role-based access control. When requireAuth is true, any request lacking the valid bearer token receives a 401 Unauthorized response. The setCORSOnAuthError helper ensures appropriate Access-Control-Allow-Origin headers are set so browsers can read the error.
Upon successful validation, the middleware injects authentication status into the request context using ctxKeyRemoteAuth = true. Downstream middleware, including host-check and CORS handlers, consult isRemoteAuth to relax restrictions for trusted remote calls.
Managing Authentication via Settings
The current token and requireAuth flag can be inspected and modified at runtime through the /api/v1/settings endpoints defined in internal/server/settings.go. The JSON structures (lines 3-28) expose these values via GET and PUT handlers, allowing dynamic reconfiguration without server restarts. The token is redacted in UI responses unless the client is a local request.
Example payload structure:
type Settings struct {
AuthToken string `json:"auth_token"`
RequireAuth bool `json:"require_auth"`
}
Summary
- AgentsView uses a shared secret bearer token scheme implemented in
internal/server/auth.goto protect REST API endpoints. - The
authMiddlewarevalidates tokens fromAuthorization: Bearerheaders or?token=query parameters for SSE endpoints (/watch,/api/v1/events). - Authentication is binary: possession of the configured
AuthTokengrants full API access whenRequireAuthis enabled. - Remote-sync routes (
/api/v1/remote-sync/) always require token validation to establish remote authentication context, even when global auth is disabled. - The system supports dynamic configuration via the
/api/v1/settingsendpoints, allowing runtime changes to authentication parameters.
Frequently Asked Questions
How do I authenticate requests to AgentsView API endpoints?
Include the bearer token in the Authorization header using the format Authorization: Bearer <your-token>. For browser-based Server-Sent Event connections to /watch or /api/v1/events, append the token as a query parameter (?token=<your-token>) because EventSource connections cannot set custom headers.
What happens if the authentication token is missing or invalid?
The server returns a 401 Unauthorized status code. According to internal/server/auth.go (lines 141-149), the setCORSOnAuthError helper adds the appropriate Access-Control-Allow-Origin header so that browsers can properly read the error response rather than receiving a network error.
Can I disable authentication for local development?
Yes. Set require_auth to false via the configuration file, environment variables, or the /api/v1/settings endpoint. When disabled, most API endpoints under /api/ are accessible without tokens, though remote-sync routes still require authentication to establish the remote context and enable machine-to-machine synchronization.
How is the authentication token stored and configured?
The token is stored in the server configuration structure (cfg.AuthToken) alongside the RequireAuth boolean. These values are initialized in cmd/agentsview/main.go from CLI flags or environment variables, and can be updated dynamically through the settings API without restarting the server.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →