Firebase Facebook login: An invalid API Key was supplied in the request - swift

Trying to get Facebook login to work with the new Firebase, but I keep getting this error: "An invalid API Key was supplied in the request."
facebookLogin.logInWithReadPermissions(["public_profile", "email", "user_friends"], fromViewController: self) { (login, error) in
if error != nil {
print("Facebook login failed. Error \(error)")
} else if login.isCancelled {
print("Facebook login was cancelled.")
} else {
let accessToken = FBSDKAccessToken.currentAccessToken().tokenString
let credential = FIRFacebookAuthProvider.credentialWithAccessToken(accessToken)
if let user = FIRAuth.auth()?.currentUser {
user.linkWithCredential(credential) { (sup, error) in
if let error = error {
print(error.localizedDescription)
return
}
}
} else {
FIRAuth.auth()?.signInWithCredential(credential) { (user, error) in
if let error = error {
// ERROR COMING FROM HERE
print(error.localizedDescription)
return
}
}
}
}
}

Follow the instructions from Google: https://support.google.com/cloud/answer/6158862?hl=en to get or create the API KEY of your iOS App.
Then you need to grab this API KEY and put it in the GoogleService-Info.plist as the:
Key: API_KEY
Value: the api key that you got.

Related

Swift Facebook Login sdk error with code 2

I am getting an error while logging in with Facebook. And it was working about 3-4 months ago.
Now I am back at developing this app again and I changed the development target to iOS 13.0 from iOS 12.0 and add the SceneDelegate and other necessary things. Actually, I don't think this is the reason but good to mention.
Now I am getting this error:
FBSDKLog: Cannot login without a valid login configuration. Please
make sure the LoginConfiguration provided is non-nil Error
Domain=com.facebook.sdk.core Code=2 "(null)"
UserInfo={com.facebook.sdk:FBSDKErrorDeveloperMessageKey=Cannot login
without a valid login configuration. Please make sure the
LoginConfiguration provided is non-nil}
while running this:
fbLoginManager.logIn(permissions: ["email, public_profile"], from: self) { (loginResult, error) in
if error != nil {
print(error!)
}
if let currentToken = AccessToken.current {
let credential = FacebookAuthProvider.credential(withAccessToken: currentToken.tokenString)
Auth.auth().signIn(with: credential) { (authResult, error) in
if let error = error {
let authError = error as NSError
print(authError)
} else {
DispatchQueue.main.async {
self.setupTabbar()
self.dismiss(animated: true, completion: nil)
}
}
}
}
}
I checked info.plist several times and apply the instructions from scratch but I am still getting this error.
I am using XCode 12.5 and Swift 5
Edit: When I remove the permissions it works but I actually need those permissions.
Solution
I changed permissions from ["email, public_profile"] to:
["email", "public_profile"]
so it looks like this:
fbLoginManager.logIn(permissions: ["email", "public_profile"], from: self) { (loginResult, error) in
if error != nil {
print(error!)
}
if let currentToken = AccessToken.current {
let credential = FacebookAuthProvider.credential(withAccessToken: currentToken.tokenString)
Auth.auth().signIn(with: credential) { (authResult, error) in
if let error = error as NSError? {
print(error)
} else {
DispatchQueue.main.async {
self.setupTabbar()
self.dismiss(animated: true, completion: nil)
}
}
}
}
}

How to get access token to GCP Identity-Aware-Proxy from iOS(Swift)

I want to get the access token to access Identity-Aware-Proxy of GCP from iOS(Swift).
I just add google-auth-library-swift pod and tried using ServiceAccountTokenProvider, and got the likely accessToken. But even when I add it to the header with Bearer keyword, I couldn't access IAP protected API.
I doubt the format of access token because when I tried with Java with this sample code , the token format is different from the one I got with swift library.
Do you know how to get access token to get access to IAP protected API?
let scopes = ["https://www.googleapis.com/auth/iam"]
guard let url = Bundle.main.url(forResource: Constants.GAE.serviceAccountCredentialJSON, withExtension: nil) else {
fatalError("Failed To read JSON")
}
guard let provider = ServiceAccountTokenProvider(credentialsURL: url, scopes: scopes) else {
fatalError("Failed To create ServiceAccountTokenProvider")
}
do {
try provider.withToken { [weak self] (token, error) in
guard let self = self else { return }
if let token = token, let accessToken = token.AccessToken {
logger.debug("GAE TOKEN with token \(accessToken)")
return
} else {
if let error = error {
print("GAE TOKEN with error \(error.localizedDescription)")
return
} else {
let error = IdentityAwareProxyError.failedToGetAccessToken
print("GAE TOKEN with error \(error.localizedDescription)")
return
}
}
}
} catch let error {
print("GAE TOKEN error \(error.localizedDescription)")
}

FirebaseAuth not creating new user from Google authentication - Swift

I am using the Google authentication to authenticate users on Firebase. The code runs without errors, however, I am not seeing any of the authenticated users under the "authentication" tab of the Firebase console. There is user activity according to the analytics, but there is no record of any of the users that sign in using the Google sign-in.
func sign(_signIn: GIDSignIn!, didSignInfor user: GIDGoogleUser!, withError error: Error!){
if let err = error {
print ("failed to log into Google", err)
return
}
guard let authentication = user.authentication else { return }
let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken,
accessToken: authentication.accessToken)
Auth.auth().signInAndRetrieveData(with: credential, completion: { (authResult, error) in
if let error = error {
print ("failed to create with google account")
return
}
// User is signed in
guard let uid = user?.userID else {
return
}
I followed the documentation on Firebase and I have enabled "Google sign-in". Thanks in advance!
I have found the answer to the issue:
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!){
if let err = error {
print ("failed to log into Google", err)
return
}
print("successfully logged into Google",user)
guard let idToken = user.authentication.idToken else {return}
guard let accessToken = user.authentication.accessToken else {return}
let credentials = GoogleAuthProvider.credential(withIDToken: idToken, accessToken: accessToken)
Auth.auth().signInAndRetrieveData(with: credentials, completion: { (user, error) in
if let err = error {
print ("failed to create with google account", err)
return
}
print("successfuly logged into Firebase with Google", user?.user.uid)
})
}
The issue was with the first line of code, where "didSignInFor" was not properly capitalized. Likewise, there was a duplicate function that was calling the same sign-in function, which may have been another issue on why users were not showing up on the "authentication" tab of the Firebase console.

Firebase and Facebook Authentication

I am trying to use Firebase and Facebook login and it is working, but when the Facebook page opens and you close it without logging in it throws an error and says "fatal error: unexpectedly found nil while unwrapping an Optional value"
The line that is highlighted as causing the error is let credential....
Here is my code:
// Login button is pressed
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
if let error = error {
print(error.localizedDescription)
} else {
let credential = FIRFacebookAuthProvider.credentialWithAccessToken(FBSDKAccessToken.currentAccessToken().tokenString)
FIRAuth.auth()?.signInWithCredential(credential) { (user, error) in
if let error = error {
print(error.localizedDescription)
} else {
self.performSegueWithIdentifier("loginSegue", sender: self)
print("Login complete")
}
}
}
}
Can someone please help me? Thanks
You need to check also if you have a user, or probably the user canceled the sign up
if let user = user {
} else {
print("Uh oh. The user cancelled the Facebook login."))
}

Get Facebook user details with swift and parse

i need to get the Facebook user information details when i login a new user through parse. at present i am logging in the new user below. can't seem to get the user details though. I've seen some code written on objective - c. most of the functions don't work anymore
The Facebook iOS sdks i am running is v4.3.0.
#IBAction func facebookButton(sender: AnyObject) {
PFFacebookUtils.logInInBackgroundWithReadPermissions(permissions) {
(user: PFUser?, error: NSError?) -> Void in
if let user = user {
if user.isNew {
println("User signed up and logged in through Facebook!")
} else {
println("User logged in through Facebook!")
}
} else {
println("Uh oh. The user cancelled the Facebook login.")
}
}
}
To get the user details you have to send a FBSDKGraphRequest after the login request.
This can be done inside the if let user = user {...} block.
// Create request for user's Facebook data
let request = FBSDKGraphRequest(graphPath:"me", parameters:nil)
// Send request to Facebook
request.startWithCompletionHandler {
(connection, result, error) in
if error != nil {
// Some error checking here
}
else if let userData = result as? [String:AnyObject] {
// Access user data
let username = userData["name"] as? String
// ....
}
}
For the new Facebook API and version of Swift 3.1 you can do something like this:
if((FBSDKAccessToken.current()) != nil) {
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id,name,first_name,last_name,email"]).start(completionHandler: {(connection, result, error) -> Void in
if(error != nil) {
print("Some error occurred.");
} else {
print(result!)
}
})
}