Skip to main content

How to Check a JWT's Issuer and Audience in Go with golang-jwt

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

golang-jwt checks a token's issuer and audience when you pass the jwt.WithIssuer and jwt.WithAudience options to ParseWithClaims. With either option, the claim also becomes required, so a token without aud fails with aud claim is required.

Syntax​

Syntax
claims := &jwt.RegisteredClaims{}
_, err := jwt.ParseWithClaims(<token>, claims, <keyFunc>,
jwt.WithValidMethods([]string{"<alg>"}),
jwt.WithIssuer("<expected iss>"),
jwt.WithAudience("<expected aud>"),
)
PartWhat it does
<keyFunc>A function that returns the key that checks the signature.
jwt.WithValidMethodsThe signing algorithms you accept.
jwt.WithIssuerThe iss the token must have.
jwt.WithAudienceAudiences you accept. The token passes when its aud contains any of them.
errnil when every check passed; otherwise it says which one failed.

The golang-jwt documentation for WithAudience: "WithAudience configures the validator to require any of the specified audiences in the aud claim. Validation will fail if the audience is not listed in the token or the aud claim is missing."

The Example​

The example signs two tokens issued by https://login.example.org: one for https://photos.example.org, and one with no audience. It parses them four times: the first token with the right issuer and audience, with the audience of another API and with another issuer, and the second token with the right values.

Prerequisites​

  • Go. This guide uses Go 1.27.4.

Step 1: Create the Project​

Terminal
mkdir demo
cd demo
go mod init example.com/demo
go get github.com/golang-jwt/jwt/v5

go mod init creates the module, and go get adds golang-jwt, version 5.4.0 here.

Step 2: Write the Code​

Create main.go:

main.go, which defines check(key, token, issuer, audience) calling ParseWithClaims with WithValidMethods, WithIssuer and WithAudience, then signs a token for the photos API and one without an audience and checks them four times.

main.go
package main

import (
"encoding/base64"
"fmt"
"os"
"time"

"github.com/golang-jwt/jwt/v5"
)

// check parses token and expects the given issuer and audience.
func check(key []byte, token, issuer, audience string) {
claims := &jwt.RegisteredClaims{}
_, err := jwt.ParseWithClaims(token, claims, func(*jwt.Token) (any, error) {
return key, nil
},
jwt.WithValidMethods([]string{"HS256"}),
jwt.WithIssuer(issuer),
jwt.WithAudience(audience),
)
if err != nil {
fmt.Println("rejected:", err)
return
}
fmt.Println("accepted: sub", claims.Subject)
}

func main() {
// The signing key: 32 random bytes, written as base64.
// It's in the code only for this example; a real app loads it from its configuration.
key, err := base64.StdEncoding.DecodeString("C4iNOOORzmu+fnrPK29yq/9n92b/zf5mOs5KvOMaY64=")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}

expires := jwt.NewNumericDate(time.Now().Add(2 * time.Hour))
token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.RegisteredClaims{
Issuer: "https://login.example.org",
Subject: "ada",
Audience: jwt.ClaimStrings{"https://photos.example.org"},
ExpiresAt: expires,
}).SignedString(key)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
noAudience, err := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.RegisteredClaims{
Issuer: "https://login.example.org",
Subject: "ada",
ExpiresAt: expires,
}).SignedString(key)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}

check(key, token, "https://login.example.org", "https://photos.example.org")
check(key, token, "https://login.example.org", "https://videos.example.org")
check(key, token, "https://other.example.org", "https://photos.example.org")
check(key, noAudience, "https://login.example.org", "https://photos.example.org")
}

Step 3: Run It​

Terminal
go run .
Output
accepted: sub ada
rejected: token has invalid claims: token has invalid audience
rejected: token has invalid claims: token has invalid issuer
rejected: token has invalid claims: token is missing required claim: aud claim is required

A zsh terminal where go run prints accepted sub ada, then rejected because the token has an invalid audience, then an invalid issuer, then because the aud claim is required.

What Happened​

  • The right issuer and audience passed.
  • The videos audience failed with token has invalid audience, wrapped in token has invalid claims.
  • Another issuer failed with token has invalid issuer.
  • The token without aud failed with token is missing required claim: aud claim is required. The documentation explains the choice: "Since this validation API is helping developers in writing secure application, we decided to REQUIRE the existence of the claim, if an audience is expected."

Without jwt.WithAudience, golang-jwt doesn't look at aud at all, so a token made for any API would pass.

Common Mistakes​

MistakeWhat happensDo this instead
Leaving out jwt.WithAudienceaud is ignored, and a token made for another API passesPass your API's audience
Comparing error messages to tell failures apartMessages can change between versionsUse errors.Is with golang-jwt's error variables
Using jwt.WithAllAudiences for one accepted audienceIt requires every listed audience to be in the tokenUse jwt.WithAudience, which accepts any of them

Troubleshooting​

SymptomLikely causeFix
token has invalid claims: token has invalid audienceThe token's aud doesn't contain your audienceCheck which API the token was made for
token has invalid claims: token has invalid issuerThe token comes from another issuerUse the issuer exactly as the token has it
token has invalid claims: token is missing required claim: aud claim is requiredThe token has no audHave the sign-in service set an audience

FAQ​

How do I tell a wrong audience from other failures in code?​

Use errors.Is. For the videos audience above, errors.Is(err, jwt.ErrTokenInvalidAudience) was true, errors.Is(err, jwt.ErrTokenInvalidClaims) was true too, and errors.Is(err, jwt.ErrTokenInvalidIssuer) was false.

Can I accept several audiences?​

Yes. jwt.WithAudience takes several values, and the token passes when its aud contains any of them.

Conclusion​

Pass jwt.WithIssuer and jwt.WithAudience to ParseWithClaims, and golang-jwt rejects tokens from other issuers, tokens made for other APIs and tokens without the claims.

Additional Resources​