Generate Apple Sign In JWT Auth Token


When implementing Apple Sign In on a website, you need a JWT auth token, but Apple only provides a .pem private key file.

Problem: Apple gives you a .pem file, but you need a JWT token for authentication.

Solution: Convert the private key to a JWT token using this Ruby script.

⚠️ Important: JWT tokens expire after 6 months maximum - you'll need to regenerate them regularly.

Step 1: Get Your Apple Credentials

You'll need these from your Apple Developer account:

  • Private Key (.pem file from Apple)
  • Key ID (from the key details page)
  • Team ID (your Apple Developer Team ID)
  • Client ID (your app's bundle identifier)

Step 2: Use the Ruby Script

require 'jwt'

# Your Apple private key as a string
private_key = <<-PEM
-----BEGIN PRIVATE KEY-----
XXX
XXX
XXX
-----END PRIVATE KEY-----
PEM

# Apple Key ID (from your developer account)
key_id = "XXX"

# Your Apple Team ID
team_id = "XXX"

# Your Client ID / service ID (usually your app bundle identifier)
client_id = "io.XXX"

# Token expiration (6 months max - Apple's limit)
iat = Time.now.to_i
exp = iat + 6 * 30 * 24 * 60 * 60 # 6 months

# JWT header
header = {
  alg: "ES256",
  kid: key_id
}

# JWT payload
payload = {
  iss: team_id,
  iat: iat,
  exp: exp,
  aud: "https://appleid.apple.com",
  sub: client_id
}

# Generate the JWT token
ecdsa_key = OpenSSL::PKey::EC.new(private_key)
token = JWT.encode(payload, ecdsa_key, 'ES256', header)

# Output the token
puts "Generated JWT:"
puts token

Step 3: Use Your JWT Token

Copy the generated token and use it in your Apple Sign In implementation.

Remember: Set a reminder to regenerate this token before it expires (6 months max).

Quick Reference

Max expiration: 6 months
Algorithm: ES256
Audience: https://appleid.apple.com

Key fields:

  • iss = Team ID
  • sub = Client ID
  • kid = Key ID (in header)
  • aud = https://appleid.apple.com