Skip to navigation

Authenticate

Configuring authentication for the Lattice SDK

Lattice supports two authentication methods: OAuth 2.0 client credentials using short-lived access token, environment token authentication, using long-lived, static access tokens.

The environment token is a long-lived, static bearer token you use the token to authenticate with Lattice. You must rotate the token before it expires:

Request (REST | gRPC) with environment token Response from Lattice App Lattice

The following steps show how to authenticate using both client credentials and long-lived environment tokens with both REST and gRPC SDKs.

Before you begin

  • Set up the Lattice SDK.
  • If you are using Lattice Sandboxes, see the Sandboxes set up guide. If you are using a Lattice deployment other than Sandboxes, obtain your Lattice endpoint and access credentials from your Anduril representative.

Get the Lattice endpoint

To store the Lattice endpoint as a system environment variable, do the following:

1

Add a system variable for your Lattice environment endpoint (hostname only):

export LATTICE_ENDPOINT=<YOUR_LATTICE_ENDPOINT>
2

To verify, run the following command to print the system environment variables to your terminal:

echo $LATTICE_ENDPOINT
<environment_id>.env.sandboxes.developer.anduril.com

Get your credentials

To store your credentials as system environment variables, do the following:

1

Client credentials

If you’re using client credentials:

export LATTICE_CLIENT_ID=<YOUR_LATTICE_CLIENT_ID>
export LATTICE_CLIENT_SECRET=<YOUR_LATTICE_CLIENT_SECRET>
2

Environment token

If you’re using a long-lived environment token:

export ENVIRONMENT_TOKEN=<YOUR_ENVIRONMENT_TOKEN>
3

Sandboxes token

If you’re connecting to Sandboxes:

export SANDBOXES_TOKEN=<YOUR_SANDBOXES_TOKEN>

This is required for Sandboxes whether you use client credentials, or an environment token. If you do not have a Sandboxes token, create a new token.

Environment token

Bearer token authentication uses a long-lived, static token to authenticate requests. Use this method when your deployment provides a static access token rather than OAuth 2.0 client credentials.

The reusable client you build in Install uses this method: its common module reads ENVIRONMENT_TOKEN and attaches it to every request, so you don’t pass the token yourself.

Using REST

The common client passes the token to the SDK client’s token option. To use it, get the client from common, then call the API:

package main
import (
"context"
"fmt"
"time"
Lattice "github.com/anduril/lattice-sdk-go/v5"
"my-lattice-app/common"
)
func main() {
// Get the client from my-lattice-app/common. It reads your environment token.
LatticeClient := common.Connect()
for {
ctx := context.Background()
entity, err := LatticeClient.Entities.GetEntity(ctx, &Lattice.GetEntityRequest{EntityID: "<ENTITY_ID>"})
if err != nil {
fmt.Printf("Error fetching entity: %v\n", err)
} else {
name := "<none>"
if n := entity.GetAliases().GetName(); n != nil {
name = *n
}
location := "<none>"
pos := entity.GetLocation().GetPosition()
if pos != nil && pos.GetLatitudeDegrees() != nil && pos.GetLongitudeDegrees() != nil {
location = fmt.Sprintf("%f, %f", *pos.GetLatitudeDegrees(), *pos.GetLongitudeDegrees())
}
fmt.Printf("Asset name | %s\n", name)
fmt.Printf("Asset location | %s\n", location)
}
time.Sleep(5 * time.Second)
}
}

Using gRPC

For gRPC, the common client attaches the bearer token as metadata on every outgoing request, with the gRPC library’s per-call credentials or interceptor mechanism. To use it, get the client from common, then call the API:

// This Go example is compatible with artifacts generated using
// the following grpc/go plugin: https://schema-registry.developer.anduril.com/anduril/lattice-sdk/sdks/main:grpc/go
package main
import (
"context"
"log"
"time"
"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/entitymanager/v1/entitymanagerv1grpc"
entitymanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/entitymanager/v1"
"my-lattice-app/common"
)
func main() {
ctx := context.Background()
// Get the connection from my-lattice-app/common. It uses your environment token.
conn := common.Dial(common.EnvironmentToken())
defer conn.Close()
client := entitymanagerv1grpc.NewEntityManagerAPIClient(conn)
// Periodically get the latest entity state
for {
entity, err := client.GetEntity(ctx, &entitymanagerv1.GetEntityRequest{
EntityId: "<ENTITY_ID>",
})
if err != nil {
log.Fatalf("Error getting entity: %v", err)
}
// Process each entity.
log.Printf("Fetching entity at location: %f %f", entity.GetEntity().GetLocation().GetPosition().LatitudeDegrees, entity.GetEntity().GetLocation().GetPosition().LongitudeDegrees)
time.Sleep(5 * time.Second)
}
}

Client credentials

OAuth 2.0 client credentials is in beta and not widely deployed in production. If you’re developing an integration in a production Lattice environment, check with your Anduril representative if OAuth 2.0 is available.

When you use OAuth, Lattice exchanges your credentials for a short-lived access token using the Lattice OAuth REST endpoint. To use client credentials, add an oauth module next to the client in your project’s common module. It builds the same client as Install, with client credentials in place of the environment token.

Using REST

The REST SDK handles fetching a new access token automatically, so the oauth module passes your client ID and secret when it creates the client:

package common
import (
"fmt"
"net/http"
"os"
"github.com/anduril/lattice-sdk-go/v5/client"
"github.com/anduril/lattice-sdk-go/v5/option"
)
// ConnectWithClientCredentials returns a Lattice client that authenticates with OAuth 2.0 client
// credentials. The SDK fetches and refreshes the access token for you. It exits if the
// environment variables are missing. Like Connect, it applies your options last.
func ConnectWithClientCredentials(opts ...option.RequestOption) *client.Client {
latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
clientID := os.Getenv("LATTICE_CLIENT_ID")
clientSecret := os.Getenv("LATTICE_CLIENT_SECRET")
// Remove sandboxesToken from the following statements if you are not developing on Sandboxes.
sandboxesToken := os.Getenv("SANDBOXES_TOKEN")
if latticeEndpoint == "" || clientID == "" || clientSecret == "" || sandboxesToken == "" {
fmt.Println("Missing required environment variables")
os.Exit(1)
}
// Remove the following header if you are not developing on Sandboxes.
headers := http.Header{}
headers.Add("Anduril-Sandbox-Authorization", fmt.Sprintf("Bearer %s", sandboxesToken))
defaults := []option.RequestOption{
option.WithClientCredentials(clientID, clientSecret),
option.WithBaseURL(fmt.Sprintf("https://%s", latticeEndpoint)),
option.WithHTTPHeader(headers),
}
return client.NewClient(append(defaults, opts...)...)
}

Then get the client from the oauth module, and call the API:

package main
import (
"context"
"fmt"
"time"
Lattice "github.com/anduril/lattice-sdk-go/v5"
"my-lattice-app/common"
)
func main() {
// Get the client from my-lattice-app/common. It authenticates with OAuth 2.0 client credentials.
LatticeClient := common.ConnectWithClientCredentials()
// Continuously get the entity
for {
// Create context for the request
ctx := context.Background()
entity, err := LatticeClient.Entities.GetEntity(
ctx,
&Lattice.GetEntityRequest{
EntityID: "<ENTITY_ID>",
},
)
if err != nil {
fmt.Printf("Error fetching entity: %v\n", err)
} else {
name := "<none>"
if n := entity.GetAliases().GetName(); n != nil {
name = *n
}
location := "<none>"
pos := entity.GetLocation().GetPosition()
if pos != nil && pos.GetLatitudeDegrees() != nil && pos.GetLongitudeDegrees() != nil {
location = fmt.Sprintf("%f, %f", *pos.GetLatitudeDegrees(), *pos.GetLongitudeDegrees())
}
fmt.Printf("Asset name | %s\n", name)
fmt.Printf("Asset location | %s\n", location)
}
// Wait before next request
time.Sleep(5 * time.Second)
}
}

Using gRPC

Since gRPC does not provide built-in OAuth token management, the oauth module implements a ClientCredentialsAuth type that fetches an access token, caches it, and refreshes it before it expires:

package common
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"strings"
"sync"
"time"
)
// ClientCredentialsAuth sends an OAuth 2.0 access token, and the Sandboxes token, with every
// request. It fetches the token from Endpoint and refreshes it 5 minutes before it expires.
type ClientCredentialsAuth struct {
ClientID string
ClientSecret string
SandboxesToken string
// Endpoint is the token URL: https://<LATTICE_ENDPOINT>/api/v1/oauth/token
Endpoint string
mu sync.Mutex
accessToken string
expiryTime time.Time
}
// TokenResponse is the response of the token endpoint.
type TokenResponse struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
TokenType string `json:"token_type"`
}
// ClientCredentials returns credentials built from your environment. It exits if the
// environment variables are missing.
func ClientCredentials() *ClientCredentialsAuth {
latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
clientID := os.Getenv("LATTICE_CLIENT_ID")
clientSecret := os.Getenv("LATTICE_CLIENT_SECRET")
// Remove sandboxesToken from the following statements if you are not developing on Sandboxes.
sandboxesToken := os.Getenv("SANDBOXES_TOKEN")
if latticeEndpoint == "" || clientID == "" || clientSecret == "" || sandboxesToken == "" {
log.Fatalf("Missing required environment variables")
}
return &ClientCredentialsAuth{
ClientID: clientID,
ClientSecret: clientSecret,
SandboxesToken: sandboxesToken,
Endpoint: fmt.Sprintf("https://%s/api/v1/oauth/token", latticeEndpoint),
}
}
// GetToken returns the cached access token, or fetches a new one if it expires within 5 minutes.
func (a *ClientCredentialsAuth) GetToken() (string, error) {
a.mu.Lock()
defer a.mu.Unlock()
if a.accessToken != "" && time.Now().Add(5*time.Minute).Before(a.expiryTime) {
return a.accessToken, nil
}
formData := url.Values{}
formData.Add("grant_type", "client_credentials")
formData.Add("client_id", a.ClientID)
formData.Add("client_secret", a.ClientSecret)
req, err := http.NewRequest("POST", a.Endpoint, strings.NewReader(formData.Encode()))
if err != nil {
return "", fmt.Errorf("failed to create token request: %w", err)
}
// Remove the following header if you are not developing on Sandboxes.
req.Header.Add("Anduril-Sandbox-Authorization", "Bearer "+a.SandboxesToken)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
httpClient := &http.Client{Timeout: 10 * time.Second}
resp, err := httpClient.Do(req)
if err != nil {
return "", fmt.Errorf("failed to make token request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
bodyBytes, _ := io.ReadAll(resp.Body)
return "", fmt.Errorf("token request failed with status %d: %s", resp.StatusCode, string(bodyBytes))
}
var tokenResp TokenResponse
if err := json.NewDecoder(resp.Body).Decode(&tokenResp); err != nil {
return "", fmt.Errorf("failed to decode token response: %w", err)
}
a.accessToken = tokenResp.AccessToken
a.expiryTime = time.Now().Add(time.Duration(tokenResp.ExpiresIn) * time.Second)
return a.accessToken, nil
}
// GetRequestMetadata implements credentials.PerRPCCredentials.
func (a *ClientCredentialsAuth) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
token, err := a.GetToken()
if err != nil {
fmt.Printf("Token refresh failed: %v\n", err)
return nil, err
}
return map[string]string{
"authorization": "Bearer " + token,
// Remove the following header if you are not developing on Sandboxes.
"anduril-sandbox-authorization": "Bearer " + a.SandboxesToken,
}, nil
}
// RequireTransportSecurity implements credentials.PerRPCCredentials.
func (a *ClientCredentialsAuth) RequireTransportSecurity() bool { return true }

Then connect with ClientCredentialsAuth in place of the environment token, and call the API:

// This Go example is compatible with artifacts generated using
// the following grpc/go plugin: https://schema-registry.developer.anduril.com/anduril/lattice-sdk/sdks/main:grpc/go
package main
import (
"context"
"log"
"time"
"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/entitymanager/v1/entitymanagerv1grpc"
entitymanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/entitymanager/v1"
"my-lattice-app/common"
)
func main() {
ctx := context.Background()
// Get the connection from my-lattice-app/common. It uses OAuth 2.0 client credentials.
conn := common.Dial(common.ClientCredentials())
defer conn.Close()
client := entitymanagerv1grpc.NewEntityManagerAPIClient(conn)
// Periodically get the latest entity state
for {
entity, err := client.GetEntity(ctx, &entitymanagerv1.GetEntityRequest{
EntityId: "<ENTITY_ID>",
})
if err != nil {
log.Fatalf("Error getting entity: %v", err)
}
// Process each entity.
log.Printf("Fetching entity at location: %f %f", entity.GetEntity().GetLocation().GetPosition().LatitudeDegrees, entity.GetEntity().GetLocation().GetPosition().LongitudeDegrees)
time.Sleep(5 * time.Second)
}
}

These examples refresh the access token before it expires, with a buffer of about five minutes. Each gRPC call asks ClientCredentialsAuth for the token, which returns the cached token or refreshes it if needed.

What’s next?