Skip to content

Instantly share code, notes, and snippets.

@tuzaiz
Created December 10, 2019 09:13
Show Gist options
  • Save tuzaiz/76794a0db9e8b2b9e08fe2375d8d3ddd to your computer and use it in GitHub Desktop.
Save tuzaiz/76794a0db9e8b2b9e08fe2375d8d3ddd to your computer and use it in GitHub Desktop.
Sign in with Apple Server Handler
const express = require('express')
const request = require('request')
const jwt = require('jsonwebtoken')
const jose = require('jose')
const app = express()
let client_id = "AppBundleID" // Maybe from client
function generateClientSecret() {
let private_key = "-----BEGIN PRIVATE KEY-----\n......\n-----END PRIVATE KEY-----" // Should store in a safe place on server side
// Generate client secret
let client_secret = jwt.sign({
iss: "YourTeamID", // Team ID, should store in server side
sub: client_id, // Bundle ID, should store in server side
aud: "https://appleid.apple.com", // Fix value
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + (60 * 60)
}, private_key, {
algorithm: 'ES256',
header: {
alg: 'ES256',
kid: "YourKeyID" // Key ID, should store in a safe place on server side
}
})
return client_secret
}
// Verify authorization api
app.get('/verify', function(req, res) {
let code = req.query.code
let userId = req.query.userid
let token = req.query.token
let email = req.query.email
let familyName = req.query.family_name
let givenName = req.query.given_name
// Fetch public key from Apple
request("https://appleid.apple.com/auth/keys", function(error, response, body) {
let jwks = jose.JWKS.asKeyStore(JSON.parse(body))
// JWS Verify
if (jose.JWS.verify(token, jwks)) {
console.log("ID Token has been Verified")
let client_secret = generateClientSecret()
// Request verification for apple api
request.post({url: "https://appleid.apple.com/auth/token", form: {
client_id: client_id,
client_secret: client_secret,
code: code,
grant_type: "authorization_code"
}}, function(err, response, body) {
console.log(body)
res.send(body)
})
} else {
console.log("Cannot Verified ID Token")
res.send(400)
}
})
})
// Refresh token demo api
app.get('/refresh', function(req, res) {
let refreshToken = req.query.refresh_token
let client_secret = generateClientSecret()
request.post({
url: "https://appleid.apple.com/auth/token", form: {
client_id: client_id,
client_secret: client_secret,
grant_type: "refresh_token",
refresh_token: refreshToken
}
}, function(err, response, body) {
console.log(body)
res.send(body)
})
})
app.listen(8888)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment