oauth

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 23, 2025 License: MIT Imports: 22 Imported by: 0

README

OAuth MCP proxy

OAuth 2.1 authentication library for Go MCP servers.

Supports both MCP SDKs:

  • mark3labs/mcp-go
  • modelcontextprotocol/go-sdk (official)

One-time setup: Configure provider + add WithOAuth() to your server. Result: All tools automatically protected with token validation and caching.

mark3labs/mcp-go
import "github.com/tuannvm/oauth-mcp-proxy/mark3labs"

_, oauthOption, _ := mark3labs.WithOAuth(mux, &oauth.Config{
    Provider: "okta",
    Issuer:   "https://your-company.okta.com",
    Audience: "api://your-mcp-server",
})

mcpServer := server.NewMCPServer("Server", "1.0.0", oauthOption)
Official SDK
import mcpoauth "github.com/tuannvm/oauth-mcp-proxy/mcp"

mcpServer := mcp.NewServer(&mcp.Implementation{...}, nil)
_, handler, _ := mcpoauth.WithOAuth(mux, cfg, mcpServer)
http.ListenAndServe(":8080", handler)

📢 Migrating from v1.x? See MIGRATION-V2.md (2 line change, ~5 min)

GitHub Workflow Status Go Version Go Report Card Go Reference GitHub Release


Why Use This Library?

  • Dual SDK support - Works with both mark3labs and official SDKs
  • Simple integration - One WithOAuth() call protects all tools
  • Zero per-tool config - All tools automatically protected
  • Fast token caching - 5-min cache, <5ms validation
  • Production ready - Security hardened, battle-tested
  • Multiple providers - HMAC, Okta, Google, Azure AD

How It Works

sequenceDiagram
    participant Client
    participant Your Server
    participant oauth-mcp-proxy
    participant OAuth Provider

    Client->>Your Server: Request with Bearer token
    Your Server->>oauth-mcp-proxy: Validate token
    oauth-mcp-proxy->>OAuth Provider: Check token (cached 5min)
    OAuth Provider->>oauth-mcp-proxy: Valid + user claims
    oauth-mcp-proxy->>Your Server: Authenticated user in context
    Your Server->>Client: Execute protected tool

What oauth-mcp-proxy does:

  1. Extracts Bearer tokens from HTTP requests
  2. Validates against your OAuth provider (with caching)
  3. Adds authenticated user to request context
  4. All your tools automatically protected

Quick Start

Using mark3labs/mcp-go
1. Install
go get github.com/tuannvm/oauth-mcp-proxy
2. Add to Your Server
import (
    oauth "github.com/tuannvm/oauth-mcp-proxy"
    "github.com/tuannvm/oauth-mcp-proxy/mark3labs"
)

mux := http.NewServeMux()

// Enable OAuth (one time setup)
_, oauthOption, _ := mark3labs.WithOAuth(mux, &oauth.Config{
    Provider: "okta",                    // or "hmac", "google", "azure"
    Issuer:   "https://your-company.okta.com",
    Audience: "api://your-mcp-server",
    ServerURL: "https://your-server.com",
})

// Create MCP server with OAuth
mcpServer := mcpserver.NewMCPServer("Server", "1.0.0", oauthOption)

// Add tools - all automatically protected
mcpServer.AddTool(myTool, myHandler)

// Setup endpoint
streamable := mcpserver.NewStreamableHTTPServer(
    mcpServer,
    mcpserver.WithHTTPContextFunc(oauth.CreateHTTPContextFunc()),
)
mux.Handle("/mcp", streamable)
3. Access Authenticated User
func myHandler(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
    user, ok := oauth.GetUserFromContext(ctx)
    if !ok {
        return nil, fmt.Errorf("authentication required")
    }
    // Use user.Username, user.Email, user.Subject
}

Using Official SDK
1. Install
go get github.com/modelcontextprotocol/go-sdk
go get github.com/tuannvm/oauth-mcp-proxy
2. Add to Your Server
import (
    "github.com/modelcontextprotocol/go-sdk/mcp"
    oauth "github.com/tuannvm/oauth-mcp-proxy"
    mcpoauth "github.com/tuannvm/oauth-mcp-proxy/mcp"
)

mux := http.NewServeMux()

// Create MCP server
mcpServer := mcp.NewServer(&mcp.Implementation{
    Name:    "my-server",
    Version: "1.0.0",
}, nil)

// Add tools
mcp.AddTool(mcpServer, &mcp.Tool{
    Name: "greet",
    Description: "Greet user",
}, func(ctx context.Context, req *mcp.CallToolRequest, params *struct{}) (*mcp.CallToolResult, any, error) {
    user, _ := oauth.GetUserFromContext(ctx)
    return &mcp.CallToolResult{
        Content: []mcp.Content{
            &mcp.TextContent{Text: "Hello, " + user.Username},
        },
    }, nil, nil
})

// Add OAuth protection
_, handler, _ := mcpoauth.WithOAuth(mux, &oauth.Config{
    Provider: "okta",
    Issuer:   "https://your-company.okta.com",
    Audience: "api://your-mcp-server",
}, mcpServer)

http.ListenAndServe(":8080", handler)

Your MCP server now requires OAuth authentication.


Examples

See examples/README.md for detailed setup guide including Okta configuration.

SDK Example Description
mark3labs Simple Minimal setup - copy/paste ready
mark3labs Advanced ConfigBuilder, multiple tools, logging
Official Simple Minimal setup - copy/paste ready
Official Advanced ConfigBuilder, multiple tools, logging

Supported Providers

Provider Best For Setup Guide
HMAC Testing, development docs/providers/HMAC.md
Okta Enterprise SSO docs/providers/OKTA.md
Google Google Workspace docs/providers/GOOGLE.md
Azure AD Microsoft 365 docs/providers/AZURE.md

Documentation

Getting Started:

Advanced:


License

MIT License - See LICENSE

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AutoDetectServerURL added in v0.1.0

func AutoDetectServerURL(host, port string, useTLS bool) string

AutoDetectServerURL constructs a server URL from components

func CreateHTTPContextFunc

func CreateHTTPContextFunc() func(context.Context, *http.Request) context.Context

CreateHTTPContextFunc creates an HTTP context function that extracts OAuth tokens from Authorization headers. Use with mcpserver.WithHTTPContextFunc() to enable token extraction from HTTP requests.

Example:

streamableServer := mcpserver.NewStreamableHTTPServer(
    mcpServer,
    mcpserver.WithHTTPContextFunc(oauth.CreateHTTPContextFunc()),
)

This extracts "Bearer <token>" from Authorization header and adds it to context via WithOAuthToken(). The OAuth middleware then retrieves it via GetOAuthToken().

func CreateRequestAuthHook deprecated

func CreateRequestAuthHook(validator provider.TokenValidator) func(context.Context, interface{}, interface{}) error

CreateRequestAuthHook creates a server-level authentication hook for all MCP requests.

Deprecated: This function cannot propagate context changes due to its signature limitation. Use WithOAuth() instead, which properly handles context propagation via tool-level middleware.

This function is a no-op that always returns nil. Authentication happens at the tool level via Server.Middleware() which can properly propagate the authenticated user in context.

func GetOAuthToken

func GetOAuthToken(ctx context.Context) (string, bool)

GetOAuthToken extracts an OAuth token from the context

func OAuthMiddleware deprecated

func OAuthMiddleware(validator provider.TokenValidator, enabled bool) func(server.ToolHandlerFunc) server.ToolHandlerFunc

OAuthMiddleware creates an authentication middleware (legacy function for compatibility).

Deprecated: Use WithOAuth() for new code. This function creates a temporary Server instance for each call and doesn't support custom logging. Kept for backward compatibility only.

Modern usage:

oauthOption, _ := oauth.WithOAuth(mux, &oauth.Config{...})
mcpServer := server.NewMCPServer("name", "1.0.0", oauthOption)

func SetupOAuth deprecated

func SetupOAuth(cfg *Config) (provider.TokenValidator, error)

SetupOAuth initializes OAuth validation and sets up OAuth configuration.

Deprecated: Use WithOAuth() for new code, which provides complete OAuth setup including middleware and HTTP handlers. This function only creates a validator and requires manual wiring.

Modern usage:

oauthOption, _ := oauth.WithOAuth(mux, &oauth.Config{...})
mcpServer := server.NewMCPServer("name", "1.0.0", oauthOption)

func WithOAuthToken

func WithOAuthToken(ctx context.Context, token string) context.Context

WithOAuthToken adds an OAuth token to the context

func WithUser added in v1.0.0

func WithUser(ctx context.Context, user *User) context.Context

WithUser adds an authenticated user to context

Types

type CachedToken

type CachedToken struct {
	User      *User
	ExpiresAt time.Time
}

CachedToken represents a cached token validation result

type Config

type Config struct {
	// OAuth settings
	Mode         string // "native" or "proxy"
	Provider     string // "hmac", "okta", "google", "azure"
	RedirectURIs string // Redirect URIs (single or comma-separated)

	// OIDC configuration
	Issuer       string
	Audience     string
	ClientID     string
	ClientSecret string

	// Server configuration
	ServerURL string // Full URL of the MCP server

	// Security
	JWTSecret []byte // For HMAC provider and state signing

	// Optional - Logging
	// Logger allows custom logging implementation. If nil, uses default logger
	// that outputs to log.Printf with level prefixes ([INFO], [ERROR], etc.).
	// Implement the Logger interface (Debug, Info, Warn, Error methods) to
	// integrate with your application's logging system (e.g., zap, logrus).
	Logger Logger
}

Config holds OAuth configuration

func FromEnv added in v0.1.0

func FromEnv() (*Config, error)

FromEnv creates a Config from environment variables

func (*Config) Validate

func (c *Config) Validate() error

Validate validates the configuration

type ConfigBuilder added in v0.1.0

type ConfigBuilder struct {
	// contains filtered or unexported fields
}

ConfigBuilder provides a fluent API for constructing OAuth Config

func NewConfigBuilder added in v0.1.0

func NewConfigBuilder() *ConfigBuilder

NewConfigBuilder creates a new ConfigBuilder

func (*ConfigBuilder) Build added in v0.1.0

func (b *ConfigBuilder) Build() (*Config, error)

Build constructs and validates the Config

func (*ConfigBuilder) WithAudience added in v0.1.0

func (b *ConfigBuilder) WithAudience(audience string) *ConfigBuilder

WithAudience sets the audience

func (*ConfigBuilder) WithClientID added in v0.1.0

func (b *ConfigBuilder) WithClientID(clientID string) *ConfigBuilder

WithClientID sets the client ID

func (*ConfigBuilder) WithClientSecret added in v0.1.0

func (b *ConfigBuilder) WithClientSecret(secret string) *ConfigBuilder

WithClientSecret sets the client secret

func (*ConfigBuilder) WithHost added in v0.1.0

func (b *ConfigBuilder) WithHost(host string) *ConfigBuilder

WithHost sets the server host (used to construct ServerURL if not set)

func (*ConfigBuilder) WithIssuer added in v0.1.0

func (b *ConfigBuilder) WithIssuer(issuer string) *ConfigBuilder

WithIssuer sets the OIDC issuer

func (*ConfigBuilder) WithJWTSecret added in v0.1.0

func (b *ConfigBuilder) WithJWTSecret(secret []byte) *ConfigBuilder

WithJWTSecret sets the JWT secret

func (*ConfigBuilder) WithLogger added in v0.1.0

func (b *ConfigBuilder) WithLogger(logger Logger) *ConfigBuilder

WithLogger sets the logger

func (*ConfigBuilder) WithMode added in v0.1.0

func (b *ConfigBuilder) WithMode(mode string) *ConfigBuilder

WithMode sets the OAuth mode ("native" or "proxy")

func (*ConfigBuilder) WithPort added in v0.1.0

func (b *ConfigBuilder) WithPort(port string) *ConfigBuilder

WithPort sets the server port (used to construct ServerURL if not set)

func (*ConfigBuilder) WithProvider added in v0.1.0

func (b *ConfigBuilder) WithProvider(provider string) *ConfigBuilder

WithProvider sets the OAuth provider ("hmac", "okta", "google", "azure")

func (*ConfigBuilder) WithRedirectURIs added in v0.1.0

func (b *ConfigBuilder) WithRedirectURIs(uris string) *ConfigBuilder

WithRedirectURIs sets the redirect URIs

func (*ConfigBuilder) WithServerURL added in v0.1.0

func (b *ConfigBuilder) WithServerURL(url string) *ConfigBuilder

WithServerURL sets the full server URL directly

func (*ConfigBuilder) WithTLS added in v0.1.0

func (b *ConfigBuilder) WithTLS(useTLS bool) *ConfigBuilder

WithTLS enables HTTPS scheme (used to construct ServerURL if not set)

type Endpoint added in v0.1.0

type Endpoint struct {
	Path        string
	Description string
}

Endpoint represents an OAuth endpoint with its path and description

type Logger

type Logger interface {
	Debug(msg string, args ...interface{}) // Debug-level logging for detailed troubleshooting
	Info(msg string, args ...interface{})  // Info-level logging for normal OAuth operations
	Warn(msg string, args ...interface{})  // Warn-level logging for security violations
	Error(msg string, args ...interface{}) // Error-level logging for OAuth failures
}

Logger interface for pluggable logging. Implement this interface to integrate oauth-mcp-proxy with your application's logging system (e.g., zap, logrus, slog). If not provided in Config, a default logger using log.Printf will be used.

Example:

type MyLogger struct{ logger *zap.Logger }
func (l *MyLogger) Info(msg string, args ...interface{}) {
    l.logger.Sugar().Infof(msg, args...)
}
// ... implement Debug, Warn, Error

cfg := &oauth.Config{
    Provider: "okta",
    Logger: &MyLogger{logger: zapLogger},
}

type OAuth2Config

type OAuth2Config struct {
	Enabled      bool
	Mode         string // "native" or "proxy"
	Provider     string
	RedirectURIs string

	// OIDC configuration
	Issuer       string
	Audience     string
	ClientID     string
	ClientSecret string

	// Server configuration
	MCPHost string
	MCPPort string
	Scheme  string

	// MCPURL is the full URL of the MCP server, used for the resource endpoint in the OAuth 2.0 Protected Resource Metadata endpoint
	MCPURL string

	// Server version
	Version string
	// contains filtered or unexported fields
}

OAuth2Config holds OAuth2 configuration

func NewOAuth2ConfigFromConfig

func NewOAuth2ConfigFromConfig(cfg *Config, version string) *OAuth2Config

NewOAuth2ConfigFromConfig creates OAuth2 config from generic Config

type OAuth2Handler

type OAuth2Handler struct {
	// contains filtered or unexported fields
}

OAuth2Handler handles OAuth2 flows using the standard library

func CreateOAuth2Handler

func CreateOAuth2Handler(cfg *Config, version string, logger Logger) *OAuth2Handler

CreateOAuth2Handler creates a new OAuth2 handler for HTTP endpoints

func NewOAuth2Handler

func NewOAuth2Handler(cfg *OAuth2Config, logger Logger) *OAuth2Handler

NewOAuth2Handler creates a new OAuth2 handler using the standard library

func (*OAuth2Handler) GetAuthorizationServerMetadata

func (h *OAuth2Handler) GetAuthorizationServerMetadata() map[string]interface{}

GetAuthorizationServerMetadata returns the OAuth 2.0 Authorization Server Metadata with conditional responses based on OAuth mode

func (*OAuth2Handler) GetConfig

func (h *OAuth2Handler) GetConfig() *OAuth2Config

GetConfig returns the OAuth2 configuration

func (*OAuth2Handler) HandleAuthorizationServerMetadata

func (h *OAuth2Handler) HandleAuthorizationServerMetadata(w http.ResponseWriter, r *http.Request)

HandleAuthorizationServerMetadata handles the standard OAuth 2.0 Authorization Server Metadata endpoint

func (*OAuth2Handler) HandleAuthorize

func (h *OAuth2Handler) HandleAuthorize(w http.ResponseWriter, r *http.Request)

HandleAuthorize handles OAuth2 authorization requests with PKCE

func (*OAuth2Handler) HandleCallback

func (h *OAuth2Handler) HandleCallback(w http.ResponseWriter, r *http.Request)

HandleCallback handles OAuth2 callback

func (*OAuth2Handler) HandleCallbackRedirect

func (h *OAuth2Handler) HandleCallbackRedirect(w http.ResponseWriter, r *http.Request)

HandleCallbackRedirect handles the /callback redirect for Claude Code compatibility

func (*OAuth2Handler) HandleJWKS

func (h *OAuth2Handler) HandleJWKS(w http.ResponseWriter, r *http.Request)

HandleJWKS handles the JWKS endpoint for proxy mode

func (*OAuth2Handler) HandleMetadata

func (h *OAuth2Handler) HandleMetadata(w http.ResponseWriter, r *http.Request)

HandleMetadata handles the legacy OAuth metadata endpoint for MCP compliance

func (*OAuth2Handler) HandleOIDCDiscovery

func (h *OAuth2Handler) HandleOIDCDiscovery(w http.ResponseWriter, r *http.Request)

HandleOIDCDiscovery handles the OIDC discovery endpoint for MCP client compatibility

func (*OAuth2Handler) HandleProtectedResourceMetadata

func (h *OAuth2Handler) HandleProtectedResourceMetadata(w http.ResponseWriter, r *http.Request)

HandleProtectedResourceMetadata handles the OAuth 2.0 Protected Resource Metadata endpoint

func (*OAuth2Handler) HandleRegister

func (h *OAuth2Handler) HandleRegister(w http.ResponseWriter, r *http.Request)

HandleRegister handles OAuth dynamic client registration for mcp-remote

func (*OAuth2Handler) HandleToken

func (h *OAuth2Handler) HandleToken(w http.ResponseWriter, r *http.Request)

HandleToken handles OAuth2 token exchange

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server represents an OAuth authentication server instance. Each Server maintains its own token cache and validator, allowing multiple independent OAuth configurations in the same application.

Create using NewServer(). Access middleware via Middleware() and register HTTP endpoints via RegisterHandlers().

func NewServer

func NewServer(cfg *Config) (*Server, error)

NewServer creates a new OAuth server with the given configuration. Validates configuration, initializes provider-specific token validator, and creates instance-scoped token cache.

Example:

server, err := oauth.NewServer(&oauth.Config{
    Provider: "okta",
    Issuer:   "https://company.okta.com",
    Audience: "api://my-server",
})

Most users should use WithOAuth() instead, which wraps NewServer() and automatically registers handlers and middleware.

func WithOAuth

func WithOAuth(mux *http.ServeMux, cfg *Config) (*Server, mcpserver.ServerOption, error)

WithOAuth returns a server option that enables OAuth authentication This is the composable API for mcp-go v0.41.1

Usage:

mux := http.NewServeMux()
oauthServer, oauthOption, err := oauth.WithOAuth(mux, &oauth.Config{...})
mcpServer := server.NewMCPServer("Server", "1.0.0", oauthOption)

This function: - Creates OAuth server instance - Registers OAuth HTTP endpoints on mux - Returns server instance and middleware as server option

The returned Server instance provides access to: - WrapHandler() - Wrap HTTP handlers with OAuth token validation - GetHTTPServerOptions() - Get StreamableHTTPServer options - LogStartup() - Log OAuth endpoint information - Discovery URL helpers (GetCallbackURL, GetMetadataURL, etc.)

Note: You must also configure HTTPContextFunc to extract the OAuth token from HTTP headers. Use GetHTTPServerOptions() or CreateHTTPContextFunc().

func (*Server) GetAllEndpoints added in v0.1.0

func (s *Server) GetAllEndpoints() []Endpoint

GetAllEndpoints returns all OAuth endpoints with descriptions

func (*Server) GetAuthorizationServerMetadataURL added in v0.1.0

func (s *Server) GetAuthorizationServerMetadataURL() string

GetAuthorizationServerMetadataURL returns the OAuth 2.0 authorization server metadata URL

func (*Server) GetAuthorizeURL added in v0.1.0

func (s *Server) GetAuthorizeURL() string

GetAuthorizeURL returns the OAuth authorization URL

func (*Server) GetCallbackURL added in v0.1.0

func (s *Server) GetCallbackURL() string

GetCallbackURL returns the OAuth callback URL

func (*Server) GetHTTPServerOptions added in v0.1.0

func (s *Server) GetHTTPServerOptions() []mcpserver.StreamableHTTPOption

GetHTTPServerOptions returns StreamableHTTPServer options needed for OAuth. Returns WithHTTPContextFunc option to extract OAuth tokens from HTTP headers. Consumers should append these to their own options when creating StreamableHTTPServer.

Example:

oauthOpts := oauthServer.GetHTTPServerOptions()
allOpts := append(oauthOpts,
    mcpserver.WithEndpointPath("/mcp"),
    mcpserver.WithStateLess(false),
)
server := mcpserver.NewStreamableHTTPServer(mcpServer, allOpts...)

func (*Server) GetOIDCDiscoveryURL added in v0.1.0

func (s *Server) GetOIDCDiscoveryURL() string

GetOIDCDiscoveryURL returns the OIDC discovery URL

func (*Server) GetProtectedResourceMetadataURL added in v0.1.0

func (s *Server) GetProtectedResourceMetadataURL() string

GetProtectedResourceMetadataURL returns the protected resource metadata URL

func (*Server) GetRegisterURL added in v0.1.0

func (s *Server) GetRegisterURL() string

GetRegisterURL returns the dynamic client registration URL

func (*Server) GetStatusString added in v0.1.0

func (s *Server) GetStatusString(useTLS bool) string

GetStatusString returns a human-readable OAuth status string

func (*Server) GetTokenURL added in v0.1.0

func (s *Server) GetTokenURL() string

GetTokenURL returns the OAuth token URL

func (*Server) LogStartup added in v0.1.0

func (s *Server) LogStartup(useTLS bool)

LogStartup logs OAuth startup information including endpoints and configuration. Set useTLS to true if using HTTPS, false for HTTP (will add warning).

func (*Server) Middleware

func (s *Server) Middleware() func(server.ToolHandlerFunc) server.ToolHandlerFunc

Middleware returns an authentication middleware for MCP tools. Validates OAuth tokens, caches results, and adds authenticated user to context.

The middleware:

  1. Extracts OAuth token from context (set by CreateHTTPContextFunc)
  2. Checks token cache (5-minute TTL)
  3. Validates token using configured provider if not cached
  4. Adds User to context via userContextKey
  5. Passes request to tool handler with authenticated context

Use GetUserFromContext(ctx) in tool handlers to access authenticated user.

Note: WithOAuth() returns this middleware wrapped as mcpserver.ServerOption. Only call directly if using NewServer() for advanced use cases.

func (*Server) RegisterHandlers

func (s *Server) RegisterHandlers(mux *http.ServeMux)

RegisterHandlers registers OAuth HTTP endpoints on the provided mux. Endpoints registered:

  • /.well-known/oauth-authorization-server - OAuth 2.0 metadata (RFC 8414)
  • /.well-known/oauth-protected-resource - Resource metadata
  • /.well-known/jwks.json - JWKS keys
  • /.well-known/openid-configuration - OIDC discovery
  • /oauth/authorize - Authorization endpoint (proxy mode)
  • /oauth/callback - Callback handler (proxy mode)
  • /oauth/token - Token exchange (proxy mode)
  • /oauth/register - Dynamic client registration

Note: WithOAuth() calls this automatically. Only call directly if using NewServer() for advanced use cases.

func (*Server) ValidateTokenCached added in v1.0.0

func (s *Server) ValidateTokenCached(ctx context.Context, token string) (*User, error)

ValidateTokenCached validates a token with caching support. This is the core validation method that SDK adapters can use.

The method:

  1. Checks token cache (5-minute TTL)
  2. Validates token using configured provider if not cached
  3. Caches validation result for future requests
  4. Returns authenticated User or error

This method is used internally by both WrapHandler and adapter middleware.

func (*Server) WrapHandler added in v0.1.0

func (s *Server) WrapHandler(next http.Handler) http.Handler

WrapHandler wraps an http.Handler with OAuth Bearer token validation. It checks for a valid Authorization header before delegating to the wrapped handler. If the token is missing or invalid, returns 401 with WWW-Authenticate headers and proper OAuth error response per RFC 6750.

This eliminates the need for consumers to manually check Bearer tokens in their HTTP handlers. Use this to wrap MCP endpoints or any protected resource.

Example:

wrappedHandler := oauthServer.WrapHandler(mcpHandler)
mux.HandleFunc("/mcp", wrappedHandler)

func (*Server) WrapHandlerFunc added in v0.1.0

func (s *Server) WrapHandlerFunc(next http.HandlerFunc) http.HandlerFunc

WrapHandlerFunc wraps an http.HandlerFunc with OAuth Bearer token validation. Convenience wrapper around WrapHandler for HandlerFunc types.

type TokenCache

type TokenCache struct {
	// contains filtered or unexported fields
}

TokenCache stores validated tokens to avoid re-validation

type User

type User = provider.User

Re-export User from provider for backwards compatibility

func GetUserFromContext

func GetUserFromContext(ctx context.Context) (*User, bool)

GetUserFromContext extracts the authenticated user from context. Returns the User and true if authentication succeeded, or nil and false otherwise.

Example:

func toolHandler(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
    user, ok := oauth.GetUserFromContext(ctx)
    if !ok {
        return nil, fmt.Errorf("authentication required")
    }
    // Use user.Subject, user.Email, user.Username
    return mcp.NewToolResultText("Hello, " + user.Username), nil
}

Directories

Path Synopsis
examples
official/simple command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL