12

How do I structure a swift POST request to satisfy the Sign In With Apple token revocation requirements?

I am not sure what form-data, client_id, client_secret, token, or token_type_hint are supposed to be. I was able to implement Sign in With Apple to create a user, but very lost on the revocation part of this.

I am looking to perform this client-side with Swift, as that would be the most convenient. Firebase may be developing a solution built into their SDK, but not sure if that is a one-size fits all solution for developers using Firebase.

https://developer.apple.com/documentation/sign_in_with_apple/revoke_tokens#url

Edit: source of requirements https://developer.apple.com/support/offering-account-deletion-in-your-app

The following functions live in the same class (ViewModel). The first does my login/registration flow. Some of the code is related to Firebase flows and can be largely ignored, but you can see I grab the token string and nonce for client_secret. The second function resembles the POST request for token revocation (which gets called from a delete account function not shown). Has anyone had success with this approach/boilerplate?

Testing the token revocation method below with a button tap in my app returns status code 400. I cannot revoke tokens with this method, and I am not sure what else to do.

public func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
    // Sign in using Firebase Auth
    if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
        guard let nonce = currentNonce else {
            print("Invalid state: A login callback was received, but no login request was sent.")
            return
        }
        
        // JWT
        guard let appleIDToken = appleIDCredential.identityToken else {
            print("Unable to fetch identity token")
            return
        }
        
        guard let idTokenString = String(data: appleIDToken, encoding: .utf8) else {
            print("Unable to serialize token string from data")
            return
        }
        
        let credential = OAuthProvider.credential(withProviderID: "apple.com", idToken: idTokenString, rawNonce: nonce)
        Auth.auth().signIn(with: credential) { result, error in
            if error != nil {
                print(error!.localizedDescription)
                return
            }
            else { // successful auth, we can now check if its a login or a registration
                guard let user = Auth.auth().currentUser else {
                    print("No user was found.")
                    return
                }
                let db = Firestore.firestore()
                let docRef = db.collection("Users").document(("\(user.uid)"))
                docRef.getDocument{ (document, error) in
                    if let document = document, document.exists {
                        // User is just logging in, their db store exists
                        print("Successful Apple login.")
                        
                        // Token revocation requirements
                        self.clientSecret = nonce
                        self.appleToken = idTokenString
                        
                        if (self.isDeletingAccount == true) {
                            print("Is deleting account.")
                            self.isReauthenticated = true
                        }
                        self.isLogged = true
                    }
                    else { // document does not exist! we are registering a new user
                        db.collection("Users").document("\(user.uid)").setData([
                            "name": "\(appleIDCredential.fullName?.givenName ?? "")"
                        ])
                        print("Successful Apple registration.")
                        
                        self.clientSecret = nonce
                        self.appleToken = idTokenString
                        
                        self.isLogged = true
                    }
                }
            }
        }
    }
}


// POST request to revoke user's Apple token from Barfix app
func appleAuthTokenRevoke(completion: (([String: Any]?, Error?) -> Void)? = nil) {
    
    let paramString: [String : Any] = [
        "client_id": Bundle.main.bundleIdentifier!, //"com.MyCompany.Name",
        "client_secret": self.clientSecret,
        "token": self.appleToken,
        "token_type_hint": "access_token"
    ]
    
    let url = URL(string: "https://appleid.apple.com/auth/revoke")!
    
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    
    do {
        request.httpBody = try JSONSerialization.data(withJSONObject: paramString, options: .prettyPrinted)
    }
    catch let error {
        print(error.localizedDescription)
        completion?(nil, error)
    }
    
    request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    
    let task =  URLSession.shared.dataTask(with: request as URLRequest)  { (data, response, error) in
        guard let response = response as? HTTPURLResponse, error == nil else {
            print("error", error ?? URLError(.badServerResponse))
            return
        }
        
        guard (200 ... 299) ~= response.statusCode else {
            print("statusCode should be 2xx, but is \(response.statusCode)")
            print("response = \(response)")
            return
        }
        
        
        if let error = error {
            print(error)
        }
        else {
            print("deleted accont")
        }
    }
    task.resume()
}
5
  • What are the "upcoming June 30th requirements"? May 27 at 3:36
  • Apps that support Sign in with Apple should use the Sign in with Apple REST API to revoke user tokens
    – Andre
    May 27 at 3:38
  • @Andre were you able to find any solution?
    – ursan526
    May 27 at 23:24
  • @ursan526 No, my attempted solution above returns status code 400
    – Andre
    Jun 20 at 1:36
  • It seems the related firebase job is working on github.com/firebase/firebase-ios-sdk/issues/…
    – zangw
    Jun 20 at 5:30

3 Answers 3

3

Note, I am not familiar with swift, please forgive me that I cannot post a good answer with swift. I found some guys are not clear about the parameters of revoke token API. Hope it will help someone who is not clear about those parameters.


The three required values ​​are required for appleid.apple.com/auth/revoke.

  • client_id: This is the App ID you can find in Apple Developer's Identifiers. Team ID is an excluded identifier.

  • client_secret: A secret JSON Web Token (JWT) that uses the Sign in with Apple private key associated with your developer account. You need to create it using JWT, and download key file from developer.apple.com/account/resources/authkeys/list

  • token: A token that requires revoke. The token is access_token or refresh_token returned from auth/token.

As for the auth/token, there are two additional parameters as below

  • code: The authorization code received in an authorization response sent to your app. The code is single-use only and valid for five minutes. Authorization code validation requests require this parameter. It is the same to the authorizationCode key of the response of apple signing, and its type is base64. It should be decoded to utf-8 before assigning to auth/token API.
  • grant_type: (Required) The grant type determines how the client app interacts with the validation server. Authorization code and refresh token validation requests require this parameter. For authorization code validation, use authorization_code. For refresh token validation requests, use refresh_token.

Finally, we could call revoke token api (appleid.apple.com/auth/revoke) successfully, and the apple id binding information is deleted under Apps Using Apple ID of Settings. And the Node.js sample could be found here


Summary the whole process as below.

  • Get authorizationCode from Apple login.
  • Get a refresh token \ access token with no expiry time using authorizationCode through auth\token
  • Revoke the refresh token or access token through token\revoke
2

For any one who wants to implement account deletion with flutter , swift or react .

Before you continue reading , take a moment to read the api requirement of two urls you will need to complete the revoking process.

The link below shows how to do this with iOS(swift) and firebase using firebase functions .And by reading it you can implement a solution with the other SDKs i.e flutter , react-native etc.

Implementing account deletion with apple and firebase

But in an attempt to summarise :-

  1. When you go through the process of setting up Sign In with Apple you will need to create a key in your apple developer account that comes in a file form which can be downloaded and should be download on to your device and looks like "*********.p8" where the * stands for a bunch of numbers and words usually representing the key.This apple refers to as the private associated key.

2.This you will use to create a Jwt using popular libraries of your own choosing .which then becomes the client_secret parameter for apple's api end point .

  1. When you then sign in a user you get an authorisation code(NB:Is the code parameter for token generation endpoint) which you will then make an api call endpoint to generate a token which then become the token parameter for the revoke endpoint .

4.Finally you call the revoke endpoint with the parameters from the above processes .

NB: I believe the solution above is so far the best way assuming that you secure your key on the server side. and unless you have a way of scrambling the key you should not attempt to store this in your project(or app).

-1

Here is some unstructured solution to give you an idea on how to implement this. In the end you are going to call AppleAuth.revokeTokens() when you need to.

import SwiftUI

struct AppleAuth {
    // IRL Use keychain for this instead
    @AppStorage("JWT_client_secret") static var clientSecret: String = ""
    @AppStorage("AppleToken") static var appleToken: String = ""
    static func revokeTokens(completion: (([String: Any]?, Error?) -> Void)? = nil) {
        
        let paramString: [String : Any] = [
            "client_id": Bundle.main.bundleIdentifier!, //"com.MyCompany.Name",
            "client_secret": clientSecret,
            "token": appleToken,
            "token_type_hint": "access_token"
        ]
        let url = URL(string: "https://appleid.apple.com/auth/revoke")!
        
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        
        do {
            request.httpBody = try JSONSerialization.data(withJSONObject:paramString, options: .prettyPrinted)
        } catch let error {
            print(error.localizedDescription)
            completion?(nil, error)
        }
        
        request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        
        let task =  URLSession.shared.dataTask(with: request as URLRequest)  { (data, response, error) in
            guard
                let response = response as? HTTPURLResponse,
                error == nil
            else {                                                               
                print("error", error ?? URLError(.badServerResponse))
                return
            }
            
            guard (200 ... 299) ~= response.statusCode else {                 
                print("statusCode should be 2xx, but is \(response.statusCode)")
                print("response = \(response)")
                return
            }
            
            
            if let error = error {
                print(error)
            }else{
                print("deleted accont")
            }
        }
        task.resume()
    }

}

For this to work you need to store tokens whenever you get authorized with Apple SignIn. Here is a rough sample of doing it:

import SwiftUI
import AuthenticationServices

struct SignInWithAppleButtonView: View {
    @State private var currentNonce: String?
    var handleResult: ((Result<Bool,Error>) -> Void)? = nil
    var body: some View {
        SignInWithAppleButton(.continue,
                              onRequest: { request in
            let nonce = AuthUtil.randomNonceString()
            currentNonce = nonce
            request.requestedScopes = [.fullName, .email]
            request.nonce = AuthUtil.sha256(nonce)
        },
                              onCompletion: { result in
            
            guard case .success(let authResult) = result,
                  let appleIDCredential = authResult.credential as? ASAuthorizationAppleIDCredential,
                  let nonce = currentNonce,
                  let idTokenString = String(data: appleIDCredential.identityToken!, encoding: .utf8)
            else { return }
            
            AppleAuth.clientSecret = nonce
            AppleAuth.appleToken = idTokenString
        })
    }
}
6
  • 1
    This doesn't work. According to the doc. client_secret string (Required) A secret JSON Web Token (JWT) that uses the Sign in with Apple private key associated with your developer account. For more information about creating client secrets, see Generate and Validate Tokens. The endpoint only accepts a client_secret that was generated using a key. credentialRevokedNotification is not fired using this method.
    – cvb
    Jun 1 at 17:54
  • 2
    How do you say that JWT_client_secret is an encoded random string? Isn't this supposed to be a JWT? what is FBAuth?
    – Sergio
    Jun 2 at 13:10
  • 2
    @Sergio. Read the document about revoking tokens and see client_secret. It's a key generated at apple and expires every 6 months. The solution does not work.
    – cvb
    Jun 2 at 15:14
  • 2
    The above code looks good but is it functional in terms of revoking user? Jun 3 at 11:34
  • 3
    How to get the client_secret? Can't find a good information how to obtain that Jun 15 at 18:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.