Services
A service is one of your own programs, such as an API, a worker, or a billing job. You give that program a secret. The program exchanges the secret for a token that lasts one hour, then sends that token when it calls your other programs.
The secret cannot invite users, list users, or change SpartanAuth settings. Those jobs belong to an API key. A person signing in belongs to the login widget and a user token.
Create the service on the app sector for that product. The tenant root does not mint service tokens. See Tenant root and app sectors.
Which jobs it is for
Section titled “Which jobs it is for”Use a service when a program you run calls another program you run, and both belong to the same app.
| Job | Use |
|---|---|
| Your API calls your worker, ledger, or billing service | A service on that app sector |
| Several replicas of one program call your other programs | One service. Every replica uses the same secret |
| Staging and production | One service on the staging app sector, and another on the production app sector |
| Job | Use this instead |
|---|---|
| Create invites, list users, or change sector settings | An API key on that sector. A tenant-root key can administer every app sector |
| A person signs in | The login widget and user introspection |
| A browser calls your API for a signed-in person | The user JWT from the widget |
| You want a public developer key for someone else’s application | This feature is for your own programs. It does not issue keys to outside developers |
| You want SpartanAuth to decide which of your programs may call which | Any service in the app sector can call the others. To accept one caller, compare serviceName in your own code |
The program proves itself with the secret you pasted. Cloud workload identity, mTLS, and SPIFFE are not a way to mint a token today. The one-hour token is what the other program sees.
A service token is rejected by POST /api/v1/introspect. An existing user check keeps treating it as signed out.
Where to configure it
Section titled “Where to configure it”- In the dashboard, select the app sector for the product. On the tenant root, the Services tab explains that you need the app sector. It does not show the form.
- Open Services.
- Name the program, for example
billing-api, and choose Create service. - Copy the secret into
SPARTANAUTH_SERVICE_SECRETon that program.
A sector admin, or a tenant-root admin, can create, roll, and delete services. The secret is shown once. The list after that shows the name, an 8-character prefix, when it was created, and when it last minted a token.
The name is 1 to 64 characters. It starts with a letter or number. The rest can be letters, numbers, spaces, periods, underscores, and hyphens. Two services in the same sector cannot use the same name, ignoring case.
The tab also shows caller and receiver snippets for Go, Node, and Python. Those snippets already contain this API address and this app sector’s ID. Paste the caller into the program that makes the request. Paste the receiver into the program that accepts it.
SPARTANAUTH_SERVICE_SECRET=<the secret from the dashboard>Keep that variable in the environment or a secrets manager. The same value goes on every replica of that program. Create a second service only when the program is different.
How a call works
Section titled “How a call works”- The caller reads
SPARTANAUTH_SERVICE_SECRETand sends it once to SpartanAuth. - SpartanAuth returns a JWT that names the service and expires in one hour.
- The caller caches that JWT and sends
Authorization: Bearer <token>to your other program. - The receiver asks SpartanAuth to check the token, caches a success until the token expires, and accepts the call when
sectorIDis this app sector.
The caller does not send the secret on the call to your other program. A leaked request token dies at its expiry. Deleting the service, or waiting out a rolled secret, stops new tokens. A receiver that already cached a success keeps accepting it until exp, which is at most one hour.
Both endpoints are public. The secret is the credential for minting. The token is the credential for the hour. Checking a token also checks that the service still exists, so decoding the JWT yourself is not a substitute for the check.
Hosted SpartanAuth uses https://api.spartanauth.com. A self-hosted API uses the address of that deployment. The snippets on the Services tab use the dashboard’s API address.
Implement the caller
Section titled “Implement the caller”Mint a token:
POST /api/v1/services/tokenX-Service-Secret: <SPARTANAUTH_SERVICE_SECRET>There is no request body. A valid secret returns HTTP 200:
{ "token": "<jwt>", "expiresIn": "3600", "serviceID": "3f2a8c1d-...", "serviceName": "billing-api", "sectorID": "a1b2c3d4-..."}expiresIn is a string of seconds. Protobuf JSON sends 64-bit numbers as strings. A missing or unknown secret returns HTTP 401. More than 1,000 mints from one secret in an hour returns HTTP 429.
Cache the token and reuse it until about five minutes before it expires. Then mint again. Send the cached token to your other program:
Authorization: Bearer <token>The Go below is the caller snippet from the Services tab, with the hosted API address. On the tab, that address is already filled in. Change package main if your program uses another package name.
// Save this next to the code that calls your other service.// Change `package main` if that program uses another package name.// Set SPARTANAUTH_SERVICE_SECRET. Use the same value on every replica.package main
import ( "context" "encoding/json" "fmt" "net/http" "os" "strconv" "sync" "time")
const spartanAPI = "https://api.spartanauth.com"
var ( svcMu sync.Mutex svcToken string svcUntil time.Time)
func spartanServiceToken(ctx context.Context) (string, error) { svcMu.Lock() defer svcMu.Unlock() if svcToken != "" && time.Until(svcUntil) > 5*time.Minute { return svcToken, nil } req, err := http.NewRequestWithContext(ctx, http.MethodPost, spartanAPI+"/api/v1/services/token", nil) if err != nil { return "", err } req.Header.Set("X-Service-Secret", os.Getenv("SPARTANAUTH_SERVICE_SECRET")) resp, err := http.DefaultClient.Do(req) if err != nil { return "", err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return "", fmt.Errorf("mint service token: %s", resp.Status) } var body struct { Token string `json:"token"` ExpiresIn string `json:"expiresIn"` } if err := json.NewDecoder(resp.Body).Decode(&body); err != nil { return "", err } seconds, err := strconv.ParseInt(body.ExpiresIn, 10, 64) if err != nil { return "", fmt.Errorf("expiresIn: %w", err) } svcToken = body.Token svcUntil = time.Now().Add(time.Duration(seconds) * time.Second) return svcToken, nil}
func setServiceAuth(req *http.Request) error { token, err := spartanServiceToken(req.Context()) if err != nil { return err } req.Header.Set("Authorization", "Bearer "+token) return nil}Node and Python on the Services tab do the same three things: read SPARTANAUTH_SERVICE_SECRET, post it in X-Service-Secret, and cache until five minutes before expiresIn runs out. expiresIn is still a string. Number(...) in JavaScript and int(...) in Python both accept it.
Implement the receiver
Section titled “Implement the receiver”Check the bearer token:
POST /api/v1/services/introspectContent-Type: application/json
{"token":"<token>"}HTTP 200 means the signature is valid and the service still exists:
{ "serviceID": "3f2a8c1d-...", "serviceName": "billing-api", "sectorID": "a1b2c3d4-...", "exp": "1717000000", "iat": "1716996400"}exp and iat are strings of unix seconds. Any other status means the token should be rejected. Cache an HTTP 200 until exp, then check again. Accept the call when sectorID is this app sector. A token from another app in your organization can still return HTTP 200.
To accept only one caller, also compare serviceName to the name you created, such as billing-api. SpartanAuth does not store a list of which service may call which.
A network failure is an outage, not a failed login. The snippets return an error for that and reject the request only when the check itself says the token is bad.
// Save this next to the code that receives the call.// Change `package main` if that program uses another package name.// If this program also calls other services, keep one spartanAPI constant.// appSectorID is this app sector. A token from another app is rejected.// To accept only one caller, also compare svc.ServiceName.package main
import ( "context" "encoding/json" "net/http" "strconv" "strings" "sync" "time")
const ( spartanAPI = "https://api.spartanauth.com" appSectorID = "your-app-sector-id")
type spartanService struct { ServiceID string `json:"serviceID"` ServiceName string `json:"serviceName"` SectorID string `json:"sectorID"` Exp int64 `json:"exp,string"` Iat int64 `json:"iat,string"`}
var ( seenMu sync.Mutex seen = map[string]spartanService{})
func lookupService(ctx context.Context, token string) (spartanService, bool, error) { seenMu.Lock() if cached, ok := seen[token]; ok && time.Now().Unix() < cached.Exp { seenMu.Unlock() return cached, true, nil } seenMu.Unlock()
body := strings.NewReader(`{"token":` + strconv.Quote(token) + `}`) req, err := http.NewRequestWithContext(ctx, http.MethodPost, spartanAPI+"/api/v1/services/introspect", body) if err != nil { return spartanService{}, false, err } req.Header.Set("Content-Type", "application/json") resp, err := http.DefaultClient.Do(req) if err != nil { return spartanService{}, false, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return spartanService{}, false, nil } var svc spartanService if err := json.NewDecoder(resp.Body).Decode(&svc); err != nil { return spartanService{}, false, err } seenMu.Lock() seen[token] = svc seenMu.Unlock() return svc, true, nil}
func requireService(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { header := r.Header.Get("Authorization") token := strings.TrimPrefix(header, "Bearer ") if token == "" || token == header { http.Error(w, "missing token", http.StatusUnauthorized) return } svc, ok, err := lookupService(r.Context(), token) if err != nil { http.Error(w, "authentication error", http.StatusInternalServerError) return } if !ok || svc.SectorID != appSectorID { http.Error(w, "invalid token", http.StatusUnauthorized) return } next.ServeHTTP(w, r) })}Replace your-app-sector-id with the app sector ID. The Services tab copies that ID in for you. The Node receiver stores the introspection JSON and compares sectorID. The Python receiver does the same with int(hit["exp"]).
If one program both sends and receives, keep a single API address constant and paste both snippets into that program.
Roll, delete, and limits
Section titled “Roll, delete, and limits”Roll secret keeps the service name and returns a new secret once. The previous secret can still mint tokens for 24 hours. Update replicas with the new secret during that day. Copy the new secret when you roll it. It is not shown again.
Delete removes the service. New mints fail, and a new introspection returns HTTP 401. A receiver that already cached a token keeps accepting it until exp. Plan on up to one hour.
Each secret can mint 1,000 tokens per hour. That covers a fleet starting up. It is not a bill. A program that mints on every request will hit HTTP 429. Cache the token.
| Action | New mints | New checks | Tokens already cached by a receiver |
|---|---|---|---|
| Roll secret | New secret works immediately. Previous secret works for 24 hours | Unchanged, while the service exists | Kept until exp |
| Delete service | Rejected | HTTP 401 | Kept until exp (at most one hour) |
Token reaches exp | Caller mints again if it still has a secret | HTTP 401 | Caller fetches a new token |
Best practices
Section titled “Best practices”| Practice | Why |
|---|---|
| One service per program, and the same secret on every replica | A second service is a second program. Extra secrets on the same program only add rotation work |
| Separate services for staging and production, on separate app sectors | A staging secret then cannot call production |
Store SPARTANAUTH_SERVICE_SECRET in a secrets manager | The secret is the long-lived credential. The token is the one you put on the wire |
| Cache the caller token until five minutes before it expires | You stay under the hourly mint limit, and SpartanAuth is not on the path of every call |
Cache a successful check until exp | The receiver stays fast, and a deleted service stops being accepted after the current token expires |
Compare sectorID to this app sector | Another app in your organization can still produce HTTP 200 |
Compare serviceName when only one program should call | SpartanAuth allows every service in the sector |
| Roll, deploy the new secret, then let the 24 hours run out | Replicas pick up the new secret while the old one still starts |
| After a delete, wait out the hour before assuming every receiver has stopped | Cached checks are valid until exp |
| Keep using user introspection for people | A service token has no user and is rejected there |
| Keep using an API key to administer SpartanAuth | A service token cannot invite users or change settings |
Related
Section titled “Related”- API keys — administer SpartanAuth
- Token verification — check a person’s JWT
- Tenant root and app sectors — which sector gets the service