How AgentsView Manages Authentication and Auth Tokens: A Complete Guide
AgentsView implements a configurable Bearer-token scheme in internal/server/auth.go that validates tokens via HTTP headers or query parameters, supporting both standard REST API requests and Server-Sent Events while allowing runtime token updates through the configuration endpoint.
The kenn-io/agentsview repository provides a lightweight HTTP API that secures access using a simple yet effective authentication layer. Understanding how AgentsView manages authentication and auth tokens is essential for production deployments, particularly when integrating with browser-based real-time event streams. The implementation spans configuration management, request middleware, and context-based security validation.
Bearer Token Configuration
The authentication system centers on two fields defined in internal/server/settings.go: AuthToken (*string) and RequireAuth (*bool). These control whether the API is open or protected, and which secret value clients must present.
Config Structure
The Config struct houses these settings alongside other server parameters. When RequireAuth is set to true, the server enforces token checking on all /api/ endpoints, while static assets and non-API paths remain accessible without authentication.
Initialization Methods
You can configure authentication at startup via environment variables, CLI flags, or JSON/YAML configuration files. The server recognizes AGENTSVIEW_AUTH_TOKEN for the secret and AGENTSVIEW_REQUIRE_AUTH as a boolean flag to enable enforcement.
The Authentication Middleware Flow
The authMiddleware function in internal/server/auth.go (lines 63-98) attaches to the router in server.go and processes every request matching the /api/ prefix. This middleware implements a multi-stage validation pipeline that balances security with practical concerns like CORS and SSE support.
Request Path Filtering
The middleware first checks strings.HasPrefix(r.URL.Path, "/api/") to determine if authentication is required. Static assets bypass the gate entirely. For CORS pre-flight OPTIONS requests, the middleware marks the request as authenticated by storing ctxKeyRemoteAuth = true in the request context, allowing downstream CORS middleware to permit the cross-origin handshake.
Token Extraction and Validation
When RequireAuth is enabled but AuthToken is empty, the server returns 500 Internal Server Error to prevent an insecure open state. For valid configurations, the middleware extracts tokens via two methods:
- Authorization Header: Standard
Bearer <token>format parsed from theAuthorizationheader. - Query Parameter:
?token=<token>for specific endpoints.
The supplied token must exactly match the configured AuthToken. On mismatch, the middleware returns 401 Unauthorized and invokes setCORSOnAuthError (lines 45-52) to ensure browser clients can read the error response.
SSE and Query Parameter Support
Browser-based EventSource connections cannot set custom HTTP headers, so AgentsView explicitly supports query parameter authentication for SSE endpoints at /watch and /api/v1/events (lines 108-119 in auth.go). This allows real-time streaming while maintaining token-based security, though header-based authentication is preferred for standard API calls.
Security Helpers and Localhost Protection
The authentication system includes helper functions that prevent token exposure and manage request context for downstream middleware.
Context-Based Auth Tracking
Successful authentication enriches the request context with ctxKeyRemoteAuth = true (lines 130-134). The isRemoteAuth(r) function reads this flag, allowing the CORS and host-checking middleware to relax restrictions for requests that have already passed token validation.
Localhost Validation
The isLocalhostRequest(r) function (lines 27-52) checks whether a request originated from a loopback address and lacks proxy forwarding headers like X-Forwarded-For. This protects sensitive configuration data, ensuring the auth token and other secrets are only exposed to local clients when appropriate. The hasForwardingHeader(r) helper detects reverse-proxy scenarios to prevent localhost bypass attacks.
Runtime Token Management
Unlike static configurations that require restarts, AgentsView supports dynamic token updates. The huma_routes_settings.go file implements a PATCH endpoint at /api/v1/config (lines 94-102) that accepts JSON patches to modify the AuthToken field. The server immediately writes the new value into the in-memory config and persists it, applying the updated token to subsequent requests without service interruption.
Implementation Examples
Configure authentication at startup using environment variables:
export AGENTSVIEW_AUTH_TOKEN=sk-agentsview-2024-secure-token
export AGENTSVIEW_REQUIRE_AUTH=true
./agentsview
Make authenticated API requests in Go:
package main
import (
"net/http"
"time"
)
func fetchSessions(token string) (*http.Response, error) {
client := &http.Client{Timeout: 10 * time.Second}
req, err := http.NewRequest("GET", "http://localhost:8080/api/v1/sessions", nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+token)
return client.Do(req)
}
Connect to the SSE stream from a browser using query parameter authentication:
const token = "sk-agentsview-2024-secure-token";
const eventSource = new EventSource(
`http://localhost:8080/api/v1/events?token=${token}`
);
eventSource.onmessage = (event) => {
console.log("Received data:", event.data);
};
eventSource.onerror = (error) => {
console.error("EventSource failed:", error);
};
Summary
- Configurable enforcement: The
RequireAuthandAuthTokenfields ininternal/server/settings.gocontrol whether and how authentication is applied. - Path-specific gating: The
authMiddlewareinauth.goonly protects/api/routes, allowing static assets to serve without tokens. - Flexible token input: Standard API calls use
Authorization: Bearerheaders, while SSE endpoints accept?token=query parameters for browserEventSourcecompatibility. - Safety checks: The server returns
500if authentication is required but no token is configured, preventing accidental open states. - Context integration: Successful auth sets
ctxKeyRemoteAuthin the request context, informing downstream CORS and host-checking middleware. - Runtime updates: Tokens can be modified via PATCH to
/api/v1/configwithout restarting the server.
Frequently Asked Questions
How do I enable authentication in AgentsView?
Set the AGENTSVIEW_AUTH_TOKEN environment variable to your secret string and set AGENTSVIEW_REQUIRE_AUTH=true before starting the binary. You can also configure these via JSON/YAML config files. Once enabled, all API requests must include the header Authorization: Bearer <token>.
Why does AgentsView accept tokens via query parameters?
Query parameter authentication (?token=<value>) is specifically implemented for Server-Sent Events endpoints because browser EventSource APIs cannot set custom HTTP headers. This enables secure real-time streaming while maintaining token-based access control, though header-based authentication is recommended for standard REST calls.
How can I update the auth token without restarting the server?
Send a JSON PATCH request to the /api/v1/config endpoint with the new token value. The handler in internal/server/huma_routes_settings.go updates the in-memory configuration immediately and persists the change, applying the new token to all subsequent requests without requiring a service restart.
What happens if RequireAuth is true but AuthToken is empty?
The server returns 500 Internal Server Error for any API request. This safety check in authMiddleware prevents the server from running in an insecure configuration where authentication is required but no validation token exists to verify client requests.
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 →