SwiftfulThinking / SwiftfulFirebaseAuth

Firebase Authentication for Swift projects.
https://www.swiftful-thinking.com
62 stars 12 forks source link

Get user's token to send it to backend via HTTPS #11

Open aynzad opened 4 months ago

aynzad commented 4 months ago

Hi, Thanks for the amazing library. I have one question (or, if it is missing, a feature request):

After the user logs in to my app, I want to send API requests to my HTTPS backend server, and I need the Firebase 'idToken' to verify my user's identity.

Is it possible to get the 'idToken' from the 'userInfo'?

SwiftfulThinking commented 4 months ago

I can make an update. How do you normally get it from Firebase auth?Sent from my iPhoneOn Jun 18, 2024, at 3:08 AM, Alireza Esfahani @.***> wrote: Hi, Thanks for the amazing library. I have one question (or, if it is missing, a feature request): After the user logs in to my app, I want to send API requests to my HTTPS backend server, and I need the Firebase 'idToken' to verify my user's identity. Is it possible to get the 'idToken' from the 'userInfo'?

—Reply to this email directly, view it on GitHub, or unsubscribe.You are receiving this because you are subscribed to this thread.Message ID: @.***>

aynzad commented 4 months ago

I have Firebase on my server with the same exact configuration, so on the server I can verify the token and get user's info, something line this:

// idToken comes from the client app
getAuth()
  .verifyIdToken(idToken)
  .then((decodedToken) => {
    const uid = decodedToken.uid;
    // ...
  })
  .catch((error) => {
    // Handle error
  });

So I'm thinking of storing idToken in client and send it via request header to the server

vamsii777 commented 4 months ago

You shouldn't store idToken as, idToken often have a very short lifetime, instead if there's a method where we can send the idToken to server would be great!

An example on retrieving the idToken after login.

do {
    let idToken = try await firebaseUser.getIDToken()
    _ = try await sendIdTokenToServer(idToken: idToken, endpoint: .authLink)
  } catch {
     print("Error retrieving Firebase ID token: \(error)")
 }

Here's an example sendIdTokenToServer

func sendIdTokenToServer(idToken: String, endpoint: Endpoint) async throws -> String {
        let networkManager = NetworkingManager.shared

        let session = URLSession.shared

        // Send the ID token to the 'authLink' endpoint
        let _: Void = try await networkManager.request(session: session, endpoint)

        // Retrieve access and refresh tokens from the 'auth' endpoint
        let tokens: AuthResponse = try await networkManager.request(session: session, .auth, type: AuthResponse.self)

        print("TOKENS: \(tokens)")

        // Save tokens securely in Keychain
        try saveTokensInKeychain(accessToken: tokens.data.accessToken, refreshToken: tokens.data.refreshToken, expiresIn: tokens.data.expires)

        return tokens.data.accessToken
    }