After successful authentication, Hanko generates a session token that is stored as a cookie. Use the session token to authenticate requests to your backend.
This guide demonstrates how to implement session token validation in Go to ensure that only properly authenticated users can access your application’s protected resources.
The following section demonstrates how to validate session tokens against the Hanko backend.
To retrieve the session token cookie, use the http.Request.Cookie() function provided by the Go standard HTTP library.
Copy
Ask AI
// SessionValidator defines the interface for session validationtype SessionValidator interface { ValidateSession(token string) (bool, error)}// HankoSessionValidator implements SessionValidatortype HankoSessionValidator struct { apiURL string}// ValidationResponse represents the Hanko API responsetype 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}