Server-Side Sign in with Apple

Nov 15 2022 · Swift 5.6, macOS 12, iOS 15, Xcode 13.3

Part 2: Add Sign in with Apple to a Website

07. Add the Sign in with Apple Button to a Website

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 06. Setting up Sign in with Apple for the Web Next episode: 08. Handle the Sign in with Apple Callback

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

It’s now time to add Sign in with Apple to the website.

struct SIWAContext: Encodable {
  let clientID: String
  let scopes: String
  let redirectURI: String
  let state: String
}
private func buildSIWAContext(on req: Request) throws -> SIWAContext {

}
let state = [UInt8].random(count: 32).base64
let scopes = "name email"
guard let clientID = Environment.get("WEBSITE_APPLICATION_IDENTIFIER") else {
    req.logger.error("WEBSITE_APPLICATION_IDENTIFIER not set")
    throw Abort(.internalServerError)
}
guard let redirectURI = Environment.get("SIWA_REDIRECT_URL") else {
    req.logger.error("SIWA_REDIRECT_URL not set")
    throw Abort(.internalServerError)
}
let siwa = SIWAContext(clientID: clientID, scopes: scopes, redirectURI: redirectURI, state: state)
return siwa
struct RegisterContext: Encodable {
  let title = "Register"
  let message: String?
  let siwaContext: SIWAContext
  
  init(message: String? = nil, siwaContext: SIWAContext) {
    self.message = message
    self.siwaContext = siwaContext
  }
}
let siwaContext = try buildSIWAContext(on: req)
let context: RegisterContext
if let message = req.query[String.self, at: "message"] {
    context = RegisterContext(message: message, siwaContext: siwaContext)
} else {
    context = RegisterContext(siwaContext: siwaContext)
}
let expiryDate = Date().addingTimeInterval(300)
let cookie = HTTPCookies.Value(string: siwaContext.state, expires: expiryDate, maxAge: 300, isHTTPOnly: true, sameSite: HTTPCookies.SameSitePolicy.none)
response.cookies["SIWA_STATE"] = cookie
struct LoginContext: Encodable {
  let title: String
  let siwaContext: SIWAContext
}
let siwaContext = try buildSIWAContext(on: req)
let context = LoginContext(title: "Log In", siwaContext: siwaContext)
let expiryDate = Date().addingTimeInterval(300)
let cookie = HTTPCookies.Value(string: siwaContext.state, expires: expiryDate, maxAge: 300, isHTTPOnly: true, sameSite: HTTPCookies.SameSitePolicy.none)
func loginHandler(_ req: Request) async throws -> Response
let response: Response = try await req.view.render("login", context).encodeResponse(for: req)
response.cookies["SIWA_STATE"] = cookie
return response
let siwaContext = try buildSIWAContext(on: req)
let context = LoginContext(title: "Log In", siwaContext: SIWAContext)
let expiryDate = Date().addingTimeInterval(300)
let cookie = HTTPCookies.Value(string: siwaContext.state, expires: expiryDate, maxAge: 300, isHTTPOnly: true, sameSite: HTTPCookies.SameSitePolicy.none)
let response: Response = try await req.view.render("login", context).encodeResponse(for: req)
response.cookies["SIWA_STATE"] = cookie
return response
<div id="appleid-signin" class="signin-button" data-color="black" data-border="true" data-type="sign in"></div>
<script type="text/javascript" src="https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js"></script>
<script type="text/javascript">
  AppleID.auth.init({
    clientId : '#(siwaContext.clientID)',
    scope : '#(siwaContext.scopes)',
    redirectURI : '#(siwaContext.redirectURI)',
    state : '#(siwaContext.state)',
    usePopup : false
  });
</script>
<div id="appleid-signin" class="signin-button" data-color="black" data-border="true" data-type="sign in"></div>
<script type="text/javascript" src="https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js"></script>
<script type="text/javascript">
  AppleID.auth.init({
    clientId : '#(siwaContext.clientID)',
    scope : '#(siwaContext.scopes)',
    redirectURI : '#(siwaContext.redirectURI)',
    state : '#(siwaContext.state)',
    usePopup : false
  });
</script>