Authentication Security & Policy Implementation
This document explains how to implement security for tokens obtained via the Auth API.
info
For an overview of the Auth API, see Auth API Implementation Guide. For login implementation, see Basic Implementation Using the Auth API.
Token Management with HttpOnly Cookies
Store the obtained tokens in HttpOnly Cookies. Compared to storing tokens in local storage, this reduces the risk of token theft from XSS (cross-site scripting) attacks.
// Function to set tokens in HttpOnly Cookies
func setTokenCookies(c echo.Context, tokens Tokens) {
// Access token
c.SetCookie(&http.Cookie{
Name: "access_token",
Value: tokens.AccessToken,
Path: "/",
HttpOnly: true,
Secure: true, // Always true in HTTPS environments
SameSite: http.SameSiteStrictMode,
MaxAge: 3600, // 1 hour
})
// Refresh token
c.SetCookie(&http.Cookie{
Name: "refresh_token",
Value: tokens.RefreshToken,
Path: "/",
HttpOnly: true,
Secure: true,
SameSite: http.SameSiteStrictMode,
MaxAge: 86400 * 30, // 30 days
})
// ID token
c.SetCookie(&http.Cookie{
Name: "id_token",
Value: tokens.IDToken,
Path: "/",
HttpOnly: true,
Secure: true,
SameSite: http.SameSiteStrictMode,
MaxAge: 3600, // 1 hour
})
}
Cookie attribute settings
| Attribute | Value | Description |
|---|---|---|
HttpOnly | true | Prevents JavaScript access; protects tokens from XSS |
Secure | true | Sends Cookies only over HTTPS (required in production) |
SameSite | Strict | Prevents Cookie sending on cross-site requests |
Path | / | Allows Cookie use across the entire application |
Note for development environments
In local development (http://localhost), you may need to set Secure to false. We recommend making this switchable via environment variables.
CSRF Protection
When using HttpOnly Cookies, CSRF (cross-site request forgery) protection is required. The sample application combines the following measures:
- SameSite Cookie attribute:
SameSite=Strictto prevent Cookies from being sent across sites - CSRF token: A server-issued CSRF token sent to the frontend and verified via a request header
// Example CSRF middleware configuration
e.Use(middleware.CSRFWithConfig(middleware.CSRFConfig{
TokenLookup: "header:X-CSRF-Token",
CookiePath: "/",
}))