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

09. Authenticate Sign in with Apple Users on the Web

Episode complete

About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous 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

The last piece of the puzzle is implementing the logic for completing the Sign in with Apple flow.

func appleAuthRedirectHandler(_ req: Request) async throws -> Response {

}
let data = try req.content.decode(SIWARedirectData.self)
guard let appIdentifier = Environment.get("WEBSITE_APPLICATION_IDENTIFIER") else {
    throw Abort(.internalServerError)
}
let siwaToken = try await req.jwt.apple.verify(data.token, applicationIdentifier: appIdentifier)
let user: User
if let userFound = try await User.query(on: req.db).filter(\.$siwaIdentifier == siwaToken.subject.value).first() {
  user = userFound
} else {

}
guard let email = data.email, let firstName = data.firstName, let lastName = data.lastName else {
  throw Abort(.badRequest)
}
if let existingUser = try await User.query(on: req.db).filter(\.$username == email).first() {

} else {

}
user = existingUser
user.siwaIdentifier = siwaToken.subject.value
try await user.save(on: req.db)
let newUser = User(name: "\(firstName) \(lastName)", username: email, password: UUID().uuidString, siwaIdentifier: siwaToken.subject.value)
try await newUser.save(on: req.db)
user = newUser
req.auth.login(user)
return req.redirect(to: "/")
authSessionsRoutes.post("login", "siwa", "handle", use: appleAuthRedirectHandler)