This article is created by Logto, an open-source solution that helps developers implement secure auth in minutes instead of months.

Encore is a backend development platform that makes it easy to build production-ready APIs and microservices.

Logto is a modern Auth0 alternative that helps you build the sign-in experience and user identity within minutes. It's particularly well-suited for protecting API services built with Encore.

This guide will show you how to integrate Logto with your Encore application to implement secure user authentication and protect your API endpoints.


Before starting this guide, please follow the Encore quick start guide to set up your initial Encore application. This guide builds upon a basic Encore application.

Logto settings

Before we begin integrating with Encore, you'll need to set up a few things in Logto:

  1. Create an account at Logto Cloud if you don't have one yet.

  2. Create an API Resource in Logto Console, this represents your Encore API service

    • Go to "API Resources" in Logto Console and create a new API
    • Set a name and API identifier (e.g., https://api.encoreapp.com)
    • Note down the API identifier on the API resource details page as we'll need it later

Logto API Resource

  1. Create an application for your frontend application
    • Go to "Applications" in Logto Console
    • Create a new application according to your frontend framework (We use React as an example, but you can create any Single-Page Application (SPA) or native app)
    • (Optional, we'll cover this later) Integrate Logto with your frontend application according to the guide in the Logto Console.
    • Note down the application ID and issuer URL on the Application details page as we'll need them later

Logto application endpoints

Setup the auth handler for your Encore API service

Now let's implement the authentication in your Encore application. We'll use Encore's built-in auth handler to validate Logto's JWT tokens.

Add these two modules in your Encore application:

$ go get github.com/golang-jwt/jwt/v5
$ go get github.com/MicahParks/keyfunc/v3

Create auth/auth.go and add the following code:

package auth

import (
    "context"
    "time"

    "encore.dev/beta/auth"
    "encore.dev/beta/errs"
    "github.com/MicahParks/keyfunc/v3"
    "github.com/golang-jwt/jwt/v5"
)

// Configuration variables for authentication
var (
  // Expected audience for the JWT, from the Logto API resource details page
    apiResourceIndicator = ""
    // The issuer URL, from the Logto application details page
    issuer = ""
    // URL to fetch JSON Web Key Set (JWKS)
    jwksUri = issuer + "/jwks"
    // Expected client ID in the token claims, from the Logto application details page
    clientId = ""
)

// RequiredClaims defines the expected structure of JWT claims
// Extends the standard JWT claims with a custom ClientID field
type RequiredClaims struct {
    ClientID string `json:"client_id"`
    jwt.RegisteredClaims
}

// AuthHandler validates JWT tokens and extracts the user ID
// Implements Encore's authentication handler interface
//
//encore:authhandler
func AuthHandler(ctx context.Context, token string) (auth.UID, error) {
    // Fetch and parse the JWKS (JSON Web Key Set) from the identity provider
    jwks, err := keyfunc.NewDefaultCtx(ctx, []string{jwksUri})
    if err != nil {
        return "", &errs.Error{
            Code:    errs.Internal,
            Message: "failed to fetch JWKS",
        }
    }

    // Parse and validate the JWT token with required claims and validation options
    parsedToken, err := jwt.ParseWithClaims(
        token,
        &RequiredClaims{},
        jwks.Keyfunc,
        // Expect the token to be intended for this API resource
        jwt.WithAudience(apiResourceIndicator),
        // Expect the token to be issued by this issuer
        jwt.WithIssuer(issuer),
        // Allow some leeway for clock skew
        jwt.WithLeeway(time.Minute*10),
    )

    // Check if there were any errors during token parsing
    if err != nil {
        return "", &errs.Error{
            Code:    errs.Unauthenticated,
            Message: "invalid token",
        }
    }

    // Verify that the client ID in the token matches the expected client ID
    if parsedToken.Claims.(*RequiredClaims).ClientID != clientId {
        return "", &errs.Error{
            Code:    errs.Unauthenticated,
            Message: "invalid token",
        }
    }

    // Extract the user ID (subject) from the token claims
    userId, err := parsedToken.Claims.GetSubject()
    if err != nil {
        return "", &errs.Error{
            Code:    errs.Unauthenticated,
            Message: "invalid token",
        }
    }

    // Return the user ID as an Encore auth.UID
    return auth.UID(userId), nil
}

And then, you can use this auth handler to protect your API endpoints:

package hello

import (
    "context"
    "fmt"

    "encore.dev/beta/auth"
    "encore.dev/beta/errs"
)

//encore:api auth method=GET path=/hello
func Hello(ctx context.Context) (*Response, error) {
    userId, hasUserId := auth.UserID()

    if !hasUserId {
        return nil, &errs.Error{
            Code:    errs.Internal,
            Message: "expect user ID",
        }
    }

    return &Response{Message: fmt.Sprintf("Hello, %s!", string(userId))}, nil
}

type Response struct {
    Message string
}

Frontend

We've completed our work in the Encore API service. Now we need to integrate Logto with our frontend application.

You can choose the framework you are using in the Logto Quick start page to integrate Logto with your frontend application. In this guide we use React as an example.

Check out the Add authentication to your React application guide to learn how to integrate Logto with your React application. In this example, you only need to complete up to the Integration section. After that, we'll demonstrate how the frontend application can obtain an access token from Logto to access the Encore API.

First, update your LogtoConfig by adding the API resource used in your Encore app to the resources field. This tells Logto that we will be requesting access tokens for this API resource (Encore API).

import { LogtoConfig } from '@logto/react';

const config: LogtoConfig = {
  // ...other configs
  resources: ['https://api.encoreapp.com'],
};

After updating the LogtoConfig, if a user is already signed in, they need to sign out and sign in again for the new LogtoConfig settings to take effect.

Once the user is logged in, you can use the getAccessToken method provided by the Logto React SDK to obtain an access token for accessing specific API resources. For example, to access the Encore API, we use https://api.encoreapp.com as the API resource identifier.

Then, add this access token to the request headers as the Authorization field in subsequent requests.

const { getAccessToken } = useLogto();
const accessToken = await getAccessToken('https://api.encoreapp.com');

// Add this access token to the request headers as the 'Authorization' field in subsequent requests
fetch('https://your-encore-api-endpoint/hello', {
  headers: {
    Authorization: `Bearer ${accessToken}`,
  },
});

That's it, you've successfully integrated Logto with your Encore application.

Explore more

If you want to use more Logto features in Encore, you can refer to the following links for more information: