> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hanko.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Integrate Hanko with a Go backend

> Learn how to validate Hanko session tokens in your Go backend to secure API endpoints and authenticate users.

<div class="hidden">
  **Hanko Backend Integration Guide**:

  **About Hanko**:

  Hanko is a modern open source authentication solution and the fastest way you integrate passkeys, 2FA, SSO, and more—with full control over your data. Move between self-hosted and Hanko Cloud anytime. No lock-in. Just Auth how it should be: secure, user friendly, and fully yours.

  **What This Guide Covers**: This guide demonstrates how to validate Hanko session tokens in your backend application. You'll learn to implement session validation, create middleware for protecting endpoints, and authenticate requests using Hanko's session management APIs.

  **Key Technologies**:

  * Server-side programming language
  * HTTP client libraries
  * Middleware frameworks
  * JSON handling
  * Hanko session validation API

  **Prerequisites**:

  * Knowledge of your chosen backend language and framework
  * Hanko Cloud account (sign up at cloud.hanko.io)
  * Frontend application with Hanko authentication

  **Integration Tasks You'll Complete**:

  * Set up Hanko API URL configuration from environment variables
  * Implement session token validation using proper data structures
  * Create reusable middleware or utilities for protecting API endpoints
  * Handle session validation responses, errors, and edge cases
  * Extract session tokens from HTTP cookies securely
  * Build authentication utilities that integrate with your application architecture
  * Implement comprehensive error handling and logging for production use
</div>

After successful authentication, Hanko generates a session token stored as a cookie. This guide shows how to validate these session tokens in your Go backend to authenticate API requests.

## Get the Hanko API URL

Retrieve your project's API URL from the [Hanko Console](https://cloud.hanko.io/). This URL is used to validate session tokens.

<Note>
  If you are self-hosting Hanko, use your self-hosted instance URL instead.
</Note>

## Authentication flow

To authenticate requests in your Go backend:

1. Extract the session token from the HTTP cookie
2. Validate the token using Hanko's [session validation API](/api-reference/public/session-management/validate-a-session-1)
3. Allow or deny the request based on validation result

## Implementation example

This example shows how to create a session validator that can be used as middleware in your Go application:

```go theme={null}
// SessionValidator defines the interface for session validation
type SessionValidator interface {
	ValidateSession(token string) (bool, error)
}

// HankoSessionValidator implements SessionValidator
type HankoSessionValidator struct {
	apiURL string
}

// ValidationResponse represents the Hanko API response
type ValidationResponse struct {
	IsValid bool `json:"is_valid"`
}

func NewHankoSessionValidator(apiURL string) *HankoSessionValidator {
	return &HankoSessionValidator{apiURL: apiURL}
}

func (v *HankoSessionValidator) ValidateSession(token string) (bool, error) {
	payload := strings.NewReader(fmt.Sprintf(`{"session_token":"%s"}`, token))

	req, err := http.NewRequest(http.MethodPost, v.apiURL+"/sessions/validate", payload)
	if err != nil {
		return false, fmt.Errorf("Failed to create request: %w", err)
	}

	req.Header.Add("Content-Type", "application/json")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		return false, fmt.Errorf("Failed to send request: %w", err)
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		return false, fmt.Errorf("Failed to read response: %w", err)
	}

	var validationRes ValidationResponse
	if err := json.Unmarshal(body, &validationRes); err != nil {
		return false, fmt.Errorf("Failed to parse response: %w", err)
	}

	return validationRes.IsValid, nil
}
```

## Using the validator as middleware

Here's how to use the session validator to protect your API endpoints:

```go theme={null}
func AuthMiddleware(validator SessionValidator) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			// Extract session token from cookie
			cookie, err := r.Cookie("hanko")
			if err != nil {
				http.Error(w, "Unauthorized", http.StatusUnauthorized)
				return
			}

			// Validate the session token
			isValid, err := validator.ValidateSession(cookie.Value)
			if err != nil {
				http.Error(w, "Internal Server Error", http.StatusInternalServerError)
				return
			}

			if !isValid {
				http.Error(w, "Unauthorized", http.StatusUnauthorized)
				return
			}

			// Continue to the next handler
			next.ServeHTTP(w, r)
		})
	}
}

// Usage example
func main() {
	validator := NewHankoSessionValidator("https://your-hanko-api-url.hanko.io")
	
	mux := http.NewServeMux()
	mux.HandleFunc("/protected", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("This is a protected endpoint!"))
	})

	// Apply authentication middleware to protected routes
	http.ListenAndServe(":8080", AuthMiddleware(validator)(mux))
}
```
