Sign in with Apple using Vapor 4

240 views Asked by At

I'm trying to implement Sign In with Apple using Vapor 4 I followed Vapor Docs But when I use the api and send user's token (even as a request header or in the body), it returns the following error

{
    "error": true,
    "reason": "Data corrupted at path ''. The given data was not valid JSON. Underlying error: Error Domain=NSCocoaErrorDomain Code=3840 \"Invalid value around line 1, column 0.\" UserInfo={NSDebugDescription=Invalid value around line 1, column 0., NSJSONSerializationErrorIndex=0}."
}

As I mentioned, I used two different method. First one, sending user token in the body:

    func SignInWithApple(req: Request)async throws -> Token{
        //Decode request body -> succeeded
        let data = try req.content.decode(SignInWithAppleToken.self)
        //The bundle id of the iOS app
        guard let appIdentifier = Environment.get("ios_app_id") else{
            throw Abort(.internalServerError)
        }
        //The error happens at this line
        let siwaToken = try await req.jwt.apple.verify(data.token, applicationIdentifier: appIdentifier)
        print(siwaToken)

//Rest of logic
}

Second one, sending user token in request header (Bearer)

func routes(_ app: Application) throws {
 app.jwt.apple.applicationIdentifier = "iOS_app_bundle_Id"
    app.get("apple") { req async throws -> HTTPStatus in
        let token = try await req.jwt.apple.verify()
        print(token) // AppleIdentityToken
        return .ok
    }
}

This how I send the request in postman: 1- Sending data in request body (for method 1): 1- Sending data in request body (for method 1):

2- Sending data in request header (for method ): 2- Sending data in request header (for method ):

Any suggestion?

1

There are 1 answers

0
Islam On

That's most likely because you're sending the identityToken as is which is Data, but you need to convert it to String before sending it to your backend with something like this:

func handleAppleSignIn(_ auth: ASAuthorization) {
    guard let credential = auth.credential as? ASAuthorizationAppleIDCredential else {
        print("Invalid Apple ID credential")
        return
    }

    guard let idToken = credential.identityToken, let idTokenString = String(data: idToken, encoding: .utf8) else {
        print("Unable to convert identityToken to String")
        return
    }

    print(idTokenString)
    // rest of the logic
}