Skip to main content

Protect your Echo API with RBAC and JWT validation

This guide will help you implement authorization to secure your Echo APIs using Role-based access control (RBAC) and JSON Web Tokens (JWTs) issued by Logto.

Before you start

Your client applications need to obtain access tokens from Logto. If you haven't set up client integration yet, check out our Quick starts for React, Vue, Angular, or other client frameworks, or see our Machine-to-machine guide for server-to-server access.

This guide focuses on the server-side validation of those tokens in your Echo application.

A figure showing the focus of this guide

What you will learn

  • JWT validation: Learn to validate access tokens and extract authentication information
  • Middleware implementation: Create reusable middleware for API protection
  • Permission models: Understand and implement different authorization patterns:
    • Global API resources for application-wide endpoints
    • Organization permissions for tenant-specific feature control
    • Organization-level API resources for multi-tenant data access
  • RBAC integration: Enforce role-based permissions and scopes in your API endpoints

Prerequisites

  • Latest stable version of Go installed
  • Basic understanding of Echo and web API development
  • A Logto application configured (see Quick starts if needed)

Permission models overview

Before implementing protection, choose the permission model that fits your application architecture. This aligns with Logto's three main authorization scenarios:

Global API resources RBAC
  • Use case: Protect API resources shared across your entire application (not organization-specific)
  • Token type: Access token with global audience
  • Examples: Public APIs, core product services, admin endpoints
  • Best for: SaaS products with APIs used by all customers, microservices without tenant isolation
  • Learn more: Protect global API resources

💡 Choose your model before proceeding - the implementation will reference your chosen approach throughout this guide.

Quick preparation steps

Configure Logto resources & permissions

  1. Create API resource: Go to Console → API resources and register your API (e.g., https://api.yourapp.com)
  2. Define permissions: Add scopes like read:products, write:orders – see Define API resources with permissions
  3. Create global roles: Go to Console → Roles and create roles that include your API permissions – see Configure global roles
  4. Assign roles: Assign roles to users or M2M applications that need API access
New to RBAC?:

Start with our Role-based access control guide for step-by-step setup instructions.

Update your client application

Request appropriate scopes in your client:

The process usually involves updating your client configuration to include one or more of the following:

  • scope parameter in OAuth flows
  • resource parameter for API resource access
  • organization_id for organization context
Before you code:

Make sure the user or M2M app you are testing has been assigned proper roles or organization roles that include the necessary permissions for your API.

Initialize your API project

To initialize a new Go project with Echo, you can follow these steps:

go mod init your-api-name
go get github.com/labstack/echo/v4

Then, create a basic Echo server setup:

main.go
package main

import (
"github.com/labstack/echo/v4"
)

func main() {
e := echo.New()

e.Logger.Fatal(e.Start(":3000"))
}
note:

Refer to the Echo documentation for more details on how to set up routes, middleware, and other features.

Initialize constants and utilities

Define necessary constants and utilities in your code to handle token extraction and validation. A valid request must include an Authorization header in the form Bearer <access_token>.

auth_middleware.go
package main

import (
"fmt"
"net/http"
"strings"
)

const (
JWKS_URI = "https://your-tenant.logto.app/oidc/jwks"
ISSUER = "https://your-tenant.logto.app/oidc"
)

type AuthorizationError struct {
Message string
Status int
}

func (e *AuthorizationError) Error() string {
return e.Message
}

func NewAuthorizationError(message string, status ...int) *AuthorizationError {
statusCode := http.StatusForbidden // Default to 403 Forbidden
if len(status) > 0 {
statusCode = status[0]
}
return &AuthorizationError{
Message: message,
Status: statusCode,
}
}

func extractBearerTokenFromHeaders(r *http.Request) (string, error) {
const bearerPrefix = "Bearer "

authorization := r.Header.Get("Authorization")
if authorization == "" {
return "", NewAuthorizationError("Authorization header is missing", http.StatusUnauthorized)
}

if !strings.HasPrefix(authorization, bearerPrefix) {
return "", NewAuthorizationError(fmt.Sprintf("Authorization header must start with \"%s\"", bearerPrefix), http.StatusUnauthorized)
}

return strings.TrimPrefix(authorization, bearerPrefix), nil
}

Retrieve info about your Logto tenant

You’ll need the following values to validate Logto-issued tokens:

  • JSON Web Key Set (JWKS) URI: The URL to Logto’s public keys, used to verify JWT signatures.
  • Issuer: The expected issuer value (Logto’s OIDC URL).

First, find your Logto tenant’s endpoint. You can find it in various places:

  • In the Logto Console, under SettingsDomains.
  • In any application settings where you configured in Logto, SettingsEndpoints & Credentials.

Fetch from OpenID Connect discovery endpoint

These values can be retrieved from Logto’s OpenID Connect discovery endpoint:

https://<your-logto-endpoint>/oidc/.well-known/openid-configuration

Here’s an example response (other fields omitted for brevity):

{
"jwks_uri": "https://your-tenant.logto.app/oidc/jwks",
"issuer": "https://your-tenant.logto.app/oidc"
}

Since Logto doesn't allow customizing the JWKS URI or issuer, you can hardcode these values in your code. However, this is not recommended for production applications as it may increase maintenance overhead if some configuration changes in the future.

  • JWKS URI: https://<your-logto-endpoint>/oidc/jwks
  • Issuer: https://<your-logto-endpoint>/oidc

Validate the token and permissions

After extracting the token and fetching the OIDC config, validate the following:

  • Signature: JWT must be valid and signed by Logto (via JWKS).
  • Issuer: Must match your Logto tenant’s issuer.
  • Audience: Must match the API’s resource indicator registered in Logto, or the organization context if applicable.
  • Expiration: Token must not be expired.
  • Permissions (scopes): Token must include required scopes for your API/action. Scopes are space-separated strings in the scope claim.
  • Organization context: If protecting organization-level API resources, validate the organization_id claim.

See JSON Web Token to learn more about JWT structure and claims.

What to check for each permission model

The claims and validation rules differ by permission model:

  • Audience claim (aud): API resource indicator
  • Organization claim (organization_id): Not present
  • Scopes (permissions) to check (scope): API resource permissions

For non-API organization permissions, the organization context is represented by the aud claim (e.g., urn:logto:organization:abc123). The organization_id claim is only present for organization-level API resource tokens.

tip:

Always validate both permissions (scopes) and context (audience, organization) for secure multi-tenant APIs.

Add the validation logic

We use github.com/lestrrat-go/jwx to validate JWTs. Install it if you haven't already:

go mod init your-project
go get github.com/lestrrat-go/jwx/v3

First, add these shared components to your auth_middleware.go:

auth_middleware.go
import (
"context"
"strings"
"time"

"github.com/lestrrat-go/jwx/v3/jwk"
"github.com/lestrrat-go/jwx/v3/jwt"
)

var jwkSet jwk.Set

func init() {
// Initialize JWKS cache
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

var err error
jwkSet, err = jwk.Fetch(ctx, JWKS_URI)
if err != nil {
panic("Failed to fetch JWKS: " + err.Error())
}
}

// validateJWT validates the JWT and returns the parsed token
func validateJWT(tokenString string) (jwt.Token, error) {
token, err := jwt.Parse([]byte(tokenString), jwt.WithKeySet(jwkSet))
if err != nil {
return nil, NewAuthorizationError("Invalid token: "+err.Error(), http.StatusUnauthorized)
}

// Verify issuer
if token.Issuer() != ISSUER {
return nil, NewAuthorizationError("Invalid issuer", http.StatusUnauthorized)
}

if err := verifyPayload(token); err != nil {
return nil, err
}

return token, nil
}

// Helper functions to extract token data
func getStringClaim(token jwt.Token, key string) string {
if val, ok := token.Get(key); ok {
if str, ok := val.(string); ok {
return str
}
}
return ""
}

func getScopesFromToken(token jwt.Token) []string {
if val, ok := token.Get("scope"); ok {
if scope, ok := val.(string); ok && scope != "" {
return strings.Split(scope, " ")
}
}
return []string{}
}

func getAudienceFromToken(token jwt.Token) []string {
return token.Audience()
}

Then, implement the middleware to verify the access token:

auth_middleware.go
import "github.com/labstack/echo/v4"

func VerifyAccessToken(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
tokenString, err := extractBearerTokenFromHeaders(c.Request())
if err != nil {
authErr := err.(*AuthorizationError)
return c.JSON(authErr.Status, echo.Map{"error": authErr.Message})
}

token, err := validateJWT(tokenString)
if err != nil {
authErr := err.(*AuthorizationError)
return c.JSON(authErr.Status, echo.Map{"error": authErr.Message})
}

// Store token in context for generic use
c.Set("auth", token)
return next(c)
}
}

According to your permission model, you may need to adopt different verifyPayload logic:

auth_middleware.go
func verifyPayload(token jwt.Token) error {
// Check audience claim matches your API resource indicator
if !hasAudience(token, "https://your-api-resource-indicator") {
return NewAuthorizationError("Invalid audience")
}

// Check required scopes for global API resources
requiredScopes := []string{"api:read", "api:write"} // Replace with your actual required scopes
if !hasRequiredScopes(token, requiredScopes) {
return NewAuthorizationError("Insufficient scope")
}

return nil
}

Add these helper functions for payload verification:

auth_middleware.go
// hasAudience checks if the token has the specified audience
func hasAudience(token jwt.Token, expectedAud string) bool {
audiences := token.Audience()
for _, aud := range audiences {
if aud == expectedAud {
return true
}
}
return false
}

// hasOrganizationAudience checks if the token has organization audience format
func hasOrganizationAudience(token jwt.Token) bool {
audiences := token.Audience()
for _, aud := range audiences {
if strings.HasPrefix(aud, "urn:logto:organization:") {
return true
}
}
return false
}

// hasRequiredScopes checks if the token has all required scopes
func hasRequiredScopes(token jwt.Token, requiredScopes []string) bool {
scopes := getScopesFromToken(token)
for _, required := range requiredScopes {
found := false
for _, scope := range scopes {
if scope == required {
found = true
break
}
}
if !found {
return false
}
}
return true
}

// hasMatchingOrganization checks if the token audience matches the expected organization
func hasMatchingOrganization(token jwt.Token, expectedOrgID string) bool {
expectedAud := fmt.Sprintf("urn:logto:organization:%s", expectedOrgID)
return hasAudience(token, expectedAud)
}

// hasMatchingOrganizationID checks if the token organization_id matches the expected one
func hasMatchingOrganizationID(token jwt.Token, expectedOrgID string) bool {
orgID := getStringClaim(token, "organization_id")
return orgID == expectedOrgID
}

Apply the middleware to your API

Now, apply the middleware to your protected API routes.

main.go
package main

import (
"net/http"

"github.com/labstack/echo/v4"
"github.com/lestrrat-go/jwx/v3/jwt"
)

func main() {
e := echo.New()

// Apply middleware to protected routes
e.GET("/api/protected", func(c echo.Context) error {
// Access token information directly from context
tokenInterface := c.Get("auth")
if tokenInterface == nil {
return c.JSON(http.StatusInternalServerError, echo.Map{"error": "Token not found"})
}

token := tokenInterface.(jwt.Token)

return c.JSON(http.StatusOK, echo.Map{
"sub": token.Subject(),
"client_id": getStringClaim(token, "client_id"),
"organization_id": getStringClaim(token, "organization_id"),
"scopes": getScopesFromToken(token),
"audience": getAudienceFromToken(token),
})
}, VerifyAccessToken)

e.Start(":8080")
}

Or using route groups:

main.go
package main

import (
"github.com/labstack/echo/v4"
"github.com/lestrrat-go/jwx/v3/jwt"
)

func main() {
e := echo.New()

// Create protected route group
api := e.Group("/api", VerifyAccessToken)
api.GET("/protected", func(c echo.Context) error {
// Access token information directly from context
token := c.Get("auth").(jwt.Token)

return c.JSON(200, echo.Map{
"sub": token.Subject(),
"client_id": getStringClaim(token, "client_id"),
"organization_id": getStringClaim(token, "organization_id"),
"scopes": getScopesFromToken(token),
"audience": getAudienceFromToken(token),
"message": "Protected data accessed successfully",
})
})

e.Start(":8080")
}

Test your protected API

Get access tokens

From your client application: If you've set up a client integration, your app can obtain tokens automatically. Extract the access token and use it in API requests.

For testing with curl/Postman:

  1. User tokens: Use your client app's developer tools to copy the access token from localStorage or the network tab

  2. Machine-to-machine tokens: Use the client credentials flow. Here's a non-normative example using curl:

    curl -X POST https://your-tenant.logto.app/oidc/token \
    -H "Content-Type: application/x-www-form-urlencoded" \
    -d "grant_type=client_credentials" \
    -d "client_id=your-m2m-client-id" \
    -d "client_secret=your-m2m-client-secret" \
    -d "resource=https://your-api-resource-indicator" \
    -d "scope=api:read api:write"

    You may need to adjust the resource and scope parameters based on your API resource and permissions; an organization_id parameter may also be required if your API is organization-scoped.

tip:

Need to inspect the token contents? Use our JWT decoder to decode and verify your JWTs.

Test protected endpoints

Valid token request
curl -H "Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9..." \
http://localhost:3000/api/protected

Expected response:

{
"auth": {
"sub": "user123",
"clientId": "app456",
"organizationId": "org789",
"scopes": ["api:read", "api:write"],
"audience": ["https://your-api-resource-indicator"]
}
}
Missing token
curl http://localhost:3000/api/protected

Expected response (401):

{
"error": "Authorization header is missing"
}
Invalid token
curl -H "Authorization: Bearer invalid-token" \
http://localhost:3000/api/protected

Expected response (401):

{
"error": "Invalid token"
}

Permission model-specific testing

Test scenarios for APIs protected with global scopes:

  • Valid scopes: Test with tokens that include your required API scopes (e.g., api:read, api:write)
  • Missing scopes: Expect 403 Forbidden when token lacks required scopes
  • Wrong audience: Expect 403 Forbidden when audience does not match the API resource
# Token with missing scopes - expect 403
curl -H "Authorization: Bearer token-without-required-scopes" \
http://localhost:3000/api/protected

Further reading

RBAC in practice: Implementing secure authorization for your application

Build a multi-tenant SaaS application: A complete guide from design to implementation