Pinterest login through app - ios

Whenever I try to authenticate with app the following msg comes:
{"status": "failure", "code": 283, "host": "coreapp-ngapi-prod-7c03bdd4", "generated_at": "Thu, 06 Aug 2015 08:02:11 +0000", "message": "The authorization grant is invalid", "data": "Invalid Application ID"}
How can I solve it?

The message is pretty explicit: Invalid Application ID.
Have you added the URL Type?
Using this initializer:
PDKClient.configureSharedInstanceWithAppId("0000")
and this OAuth:
let permission = [PDKClientReadPublicPermissions]
PDKClient.sharedInstance().authenticateWithPermissions(permission,
withSuccess: { (pdk :PDKResponseObject!) -> Void in
println("success PDKResponseObject: \(pdk)")
}) { (err :NSError!) -> Void in
println("error NSError: \(err)")
}
and assuming your client_id is correct, you should be in business.

Related

Firebase AppCheck on iOS: 403 permission errors - PERMISSION_DENIED

Q:
How can permission errors be resolved for Firebase App Check?
Background:
I have enabled App Check per the documents:
DeviceCheck is enabled/configured per:
https://firebase.google.com/docs/app-check/ios/devicecheck-provider
App Attest is enabled configured per:
https://firebase.google.com/docs/app-check/ios/devicecheck-provider
SDK is added to the project, with code from:
https://github.com/firebase/firebase-ios-sdk/blob/master/FirebaseAppCheck/Apps/FIRAppCheckTestApp/FIRAppCheckTestApp/AppDelegate.swift
Specifically, in appdelegate:
Token setup:
FirebaseApp.configure()
requestDeviceCheckToken()
requestDebugToken()
if #available(iOS 14.0, *) {
requestAppAttestToken()
}
calling:
// MARK: App Check providers
func requestDeviceCheckToken() {
guard let firebaseApp = FirebaseApp.app() else {
return
}
DeviceCheckProvider(app: firebaseApp)?.getToken { token, error in
if let token = token {
print("DeviceCheck token: \(token.token), expiration date: \(token.expirationDate)")
}
if let error = error {
print("DeviceCheck error: \((error as NSError).userInfo)")
}
}
}
func requestDebugToken() {
guard let firebaseApp = FirebaseApp.app() else {
return
}
if let debugProvider = AppCheckDebugProvider(app: firebaseApp) {
print("Debug token: \(debugProvider.currentDebugToken())")
debugProvider.getToken { token, error in
if let token = token {
print("Debug FAC token: \(token.token), expiration date: \(token.expirationDate)")
}
if let error = error {
print("Debug error: \(error)")
}
}
}
}
#available(iOS 14.0, *)
func requestAppAttestToken() {
guard let firebaseApp = FirebaseApp.app() else {
return
}
guard let appAttestProvider = AppAttestProvider(app: firebaseApp) else {
print("Failed to instantiate AppAttestProvider")
return
}
appAttestProvider.getToken { token, error in
if let token = token {
print("App Attest FAC token: \(token.token), expiration date: \(token.expirationDate)")
}
if let error = error {
print("App Attest error: \(error)")
}
}
}
requestDeviceCheckToken()returns a permissions error:
DeviceCheck error: ["NSLocalizedFailureReason": The server responded with an error:
- URL: https://firebaseappcheck.googleapis.com/v1beta/projects/<GOOGLE_APP_ID>:exchangeDeviceCheckToken
- HTTP status code: 403
- Response body: {
"error": {
"code": 403,
"message": "Requests from this iOS client application \u003cempty\u003e are blocked.",
"status": "PERMISSION_DENIED",
"details": [
{
"#type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": "API_KEY_IOS_APP_BLOCKED",
"domain": "googleapis.com",
"metadata": {
"service": "firebaseappcheck.googleapis.com",
"consumer": "projects/<my project #>"
}
}
]
}
}
requestDebugToken() returns a permissions error:
Debug error: Error Domain=com.firebase.appCheck Code=0 "The server responded with an error:
- URL: https://firebaseappcheck.googleapis.com/v1beta/projects/<GOOGLE_APP_ID>:exchangeDebugToken
- HTTP status code: 403
- Response body: {
"error": {
"code": 403,
"message": "Requests from this iOS client application \u003cempty\u003e are blocked.",
"status": "PERMISSION_DENIED",
"details": [
{
"#type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": "API_KEY_IOS_APP_BLOCKED",
"domain": "googleapis.com",
"metadata": {
"consumer": "projects/<my project #>",
"service": "firebaseappcheck.googleapis.com"
}
}
]
}
}
" UserInfo={NSLocalizedFailureReason=The server responded with an error:
- URL: https://firebaseappcheck.googleapis.com/v1beta/projects/<GOOGLE_APP_ID>:exchangeDebugToken
- HTTP status code: 403
- Response body: {
"error": {
"code": 403,
"message": "Requests from this iOS client application \u003cempty\u003e are blocked.",
"status": "PERMISSION_DENIED",
"details": [
{
"#type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": "API_KEY_IOS_APP_BLOCKED",
"domain": "googleapis.com",
"metadata": {
"consumer": "projects/<my project #",
"service": "firebaseappcheck.googleapis.com"
}
}
]
}
}
}
requestAppAttestToken() returns an error:
App Attest error: Error Domain=com.firebase.appCheck Code=0 "(null)"
GCP Console does show all calls to the following w/ 100% errors:
google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeDebugToken
google.firebase.appcheck.v1beta.TokenExchangeService.ExchangeDeviceCheckToken
google.firebase.appcheck.v1beta.TokenExchangeService.GenerateAppAttestChallenge
All of which seem to point to a permissions error? Specifically, GOOGLE_APP_ID is in the request URL, but App Check is configured in Firebase via the console...
I'm not seeing anything in the docs or anything obvious in IAM that I missed? :(
Ty in advance for help!
Update
After further testing w/ Postman:
The issue seems to be that the SDK isn't passing the X-Ios-Bundle-Identifier correctly when calling AppCheck API(s).
Steps to get to this conclusion:
From POSTMAN: API call w/ original API_KEY -> yields initial (above) error response/403
From POSTMAN: API call as above, + X-Ios-Bundle-Identifier + valid debug_token -> yields success payload.
So:
any ideas to help ID why the X-Ios-Bundle-Identifier isn't being passed by the SDK? The app is using other Firebase API's w/out issue, so seems limited to the AppCheck SDK...
and/or - can the X-Ios-Bundle-Identifier be programmatically added (in Swift) to the AppCheck calls (it is properly notated in the .plist)
Resolved!
App Check SDK does not currently support the Android / iOS Application Restriction for API keys. With that, you must remove the App Restriction for your API keys to resolve this issue.
Hopefully, the Application Restriction(s) will be supported at some point...
Update!
v8.8.0-beta now supports the bundle ID! :)
1. Configure the private key for DeviceCheck
Make sure you have created a private key for DeviceCheck
And installed it in firebase project settings under AppCheck tab
https://firebase.google.com/docs/app-check/ios/devicecheck-provider
2. Add debug token to firebase.
If you use AppCheckDebugProvider (basically for simulators), after run the project you will see a debug token in the console, you need to copy it and add to AppCheck of the project settings. Than AppCheck will approve it. Also don't forget to add -FIRDebugEnabled for the Arguments Passed on Launch.
https://firebase.google.com/docs/app-check/ios/debug-provider
3. Add production entitlements for AppAttest environment.
The beta version of AppCheck doesn't work with the AppAttest development environment, so you need to setup the production environment in your entitlements. By default, AppAttest works in a development environment, and regardless of your choice in the market it will work with a production.
https://firebase.google.com/docs/app-check/ios/app-attest-provider
https://developer.apple.com/documentation/bundleresources/entitlements/com_apple_developer_devicecheck_appattest-environment
4. Optional:
You can simplify the code
#if targetEnvironment (simulator)
let providerFactory = AppCheckDebugProviderFactory ()
#else
let providerFactory = CustomAppCheckProviderFactory ()
#endif
AppCheck.setAppCheckProviderFactory (providerFactory)
And getting a token
if let fbApp = FirebaseApp.app () {
providerFactory.createProvider(with: fbApp)?.getToken { token, error in
if let token = token {
print ("AppCheck token: \ (token.token), expiration date: \ (token.expirationDate)")
} else if let error = error {
print ("AppCheck error: \ (error as NSError).userInfo)")
}
}
}
Or if you want to protect non-firebase resources, you can get a token like this:
AppCheck.appCheck().token (forcingRefresh: false) { token, error in
if let token = token {
print ("AppCheck token: \ (token.token), expiration date: \ (token.expirationDate)")
} else if let error = error {
print ("AppCheck error: \ (error as NSError).userInfo)")
}
}
https://firebase.google.com/docs/app-check/ios/custom-resource
App Check SDK does not currently support the Android / iOS Application Restriction for API keys. With that, you must remove the App Restriction for your API keys to resolve this issue.
Hopefully, the Application Restriction(s) will be supported at some point...
Got this error - here is what worked for me:
Run app on real Android device
Opened Android Studio → Logcat → search for “DebugAppCheckProvider” → copy the debug secret
In Firebase Go to “App Check” → Apps → 3 dot menu → Manage debug token → Add token → name it → paste the debug secret
Add console log of the token after activation of app check.
try {
await firebase.appCheck().activate("ignored", true);
const token = await getAppCheckToken();
console.log({ token });
} catch (err) {
console.error(err);
}
};

LinkedIn login with custom token ( ERROR_INVALID_CUSTOM_TOKEN )

I am trying to login with LinkedIn using the native app and the LinkedIn SDK. So far I can login using the web if the LinkedIn app is not installed. I can also login with LinkedIn and get a token in return. But when I try to authenticate with Firebase I get this error:
Optional(Error Domain=FIRAuthErrorDomain Code=17000 "The custom token
format is incorrect. Please check the documentation." UserInfo=
{NSLocalizedDescription=The custom token format is incorrect. Please
check the documentation., error_name=ERROR_INVALID_CUSTOM_TOKEN})
This is my code:
// App installed
let permissions = [LISDK_BASIC_PROFILE_PERMISSION,LISDK_EMAILADDRESS_PERMISSION]
LISDKSessionManager.createSession(withAuth: permissions, state: nil, showGoToAppStoreDialog: true, successBlock: { (returnState) -> Void in
LISDKAPIHelper.sharedInstance().getRequest("https://api.linkedin.com/v1/people/~:(id,first-name,last-name,email-address,picture-url,public-profile-url,industry,positions,location)?format=json", success: { (response) -> Void in
if let data = response?.data.data(using: String.Encoding.utf8) {
if let dictResponse = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers){
let token = LISDKSessionManager.sharedInstance().session.accessToken.accessTokenValue
Auth.auth().signIn(withCustomToken: token! ) { (user, error) in
print(user!)
print(error!)
}
}
}
}, error: { (error) -> Void in
print("LINKEDIN error\(String(describing: error))")
})
}) { (error) -> Void in
print("error login linkedin")
}
The token I am sending to Firebase is a String, so that should be okay. I must be missing something. But what ?
The problem was my misunderstanding. I thought I could use the Linkedin token directly. It has to go to a webservice that uses the Firebase admin user to generate the token.

Delegation from Auth0 to Firebase does not function

I have a firebase app. Authentication provider is Auth0, all my users are residing in auth0. I am trying to login with auth0 and than with delegation creating a jwt token to use in firebase. But from firebase I am getting an error.
The error is
Login Error happened: Optional(Error Domain=FIRAuthErrorDomain Code=17999 "An internal error has occurred, print and inspect the error details for more information." UserInfo={NSUnderlyingError=0x618000252ed0 {Error Domain=FIRAuthInternalErrorDomain Code=3 "(null)" UserInfo={FIRAuthErrorUserInfoDeserializedResponseKey={
code = 400;
errors = (
{
domain = usageLimits;
message = "Bad Request";
reason = keyExpired;
}
);
message = "Bad Request"; }}}, error_name=ERROR_INTERNAL_ERROR, NSLocalizedDescription=An internal error has occurred, print and inspect the error details for more information.})
However, the JWT is okay and the id_token is not expired. The payload is
{
"uid": "auth0|58f1d133c6623f69e82eaccd",
"iat": 1492376288,
"exp": 1492379888,
"aud": "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",
"iss": "firebase-adminsdk-b69t9#mein-dienstplan-6cd8e.iam.gserviceaccount.com",
"sub": "firebase-adminsdk-b69t9#mein-dienstplan-6cd8e.iam.gserviceaccount.com"
}
The code segment show, what I am doing after authenticating teh user with email/password and getting the id_token,
Auth0
.authentication()
.delegation(withParameters: ["id_token": self.id_token!,
"target_client": "116821977303633943003",
"grant_type" : "urn:ietf:params:oauth:grant-type:jwt-bearer",
"scope": "openid profile",
"api_type": "firebase"])
.start { result in
switch(result) {
case .success(let credentials):
if let idToken = credentials["id_token"] as? String {
print("FIREBASE TOKEN = \(idToken)")
FIRAuth.auth()?.signIn(withCustomToken: idToken) { (user, error) in
guard let user = user else {
callback(error)
return
}
print("Firebase user \(user)")
callback(nil)
}
callback(nil)
} else {
callback(UserSessionError.noIdToken)
}
case .failure(let error):
callback(error)
}
}
This code brings the error above.
Anyone has any idea what is wrong ? Thx in advance...

How to retrieve Email from Facebook SDK

Note: please do not close as duplicate, I went through almost every existing thread here on Stackoverflow, but my problem is still not solved.
This is my Swift 3 function with the latest Facebook SDK:
let req = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"email,name"], tokenString: token?.tokenString, version: nil, httpMethod: "GET")
_ = req?.start(completionHandler: { (connection, result, error : Error?) -> Void in
if(error == nil) {
print("result \(result)")
} else {
print("error \(error!)")
}
})
Result:
result Optional({
id = 102080884567XXXXX;
name = "David Seek";
})
Email permission is approved:
Also the App is in live mode:
I have checked the reference guide, but I can't find my mistake.
My problem is, that I'm saving the facebookID as Email adress into my backend and I'm trying to figure out why... Therefore I have tried the provided code on top, but I'm not receiving the Email.
let result = FBSDKApplicationDelegate.sharedInstance().application(application,
open: url,
sourceApplication: sourceApplication,
annotation: annotation)
if result {
let token = FBSDKAccessToken.current()
let fieldsMapping = [
"id" : "facebookId",
"name" : "name",
"birthday": "birthday",
"first_name": "fb_first_name",
"last_name" : "fb_last_name",
"gender": "gender",
"email": "email"
]
backendless?.userService.login(withFacebookSDK: token, fieldsMapping: fieldsMapping, response: { (user: BackendlessUser?) in
}, error: { (fault: Fault?) -> Void in
print("Server reported an error: \(fault)")
})
}
I'm receiving every information, but the Email...
What am I missing? Help is very appreciated.
Email permission is granted:
That is not what that screenshot shows. It shows that it is approved, meaning your app can ask users for it. But it still has to ask.
Make sure that has happend successfully - either by debugging the access token, or via an API call to /me/permissions
You need to ask the user for permission during login.

Error code 403 when using guest authentication with TwitterKit iOS for getting user timeline

I am using Fabric's twitter kit for getting a username's tweets in my iOS application by making a request to the REST API endpoint "https://api.twitter.com/1.1/statuses/user_timeline.json"
I am have correctly set up my "consumer key" and "consumer secret key" as provided by the Fabric app in my AppDelegate and info.plist , but I repeatedly get the following error message -
Error: Optional(Error Domain=TwitterAPIErrorDomain Code=200 "Request
failed: forbidden (403)"
UserInfo={NSErrorFailingURLKey=https://api.twitter.com/1.1/guest/activate.json,
NSLocalizedDescription=Request failed: forbidden (403),
NSLocalizedFailureReason=Twitter API error : Forbidden. (code 200)})
My code is as under follows -
Twitter.sharedInstance().startWithConsumerKey(TWITTER_CONSUMER_KEY, consumerSecret: TWITTER_CONSUMER_KEY_SECRET)
Fabric.with([Twitter.sharedInstance()])
let userId = Twitter.sharedInstance().sessionStore.session()?.userID
let client = TWTRAPIClient.init(userID: userId)
let params = ["screen_name": twitterUsername, "count" : "10"]
var clientError : NSError?
let request = client.URLRequestWithMethod("GET", URL: TWITTER_TIMELINE_ENDPOINT, parameters: params, error: &clientError)
client.sendTwitterRequest(request) { (response, data, connectionError) -> Void in
if(connectionError == nil) {
self.twitterJson = self.nsdataToJSON(data!)!
self.constructTweetView(self.twitterJson)
}
else {
print("Error: \(connectionError)")
}
I am on the most recent version of TwitterKit(>2.0)
How can I go about resolving this ?
Thanks!
Add key in exception domains as shown in info.plist. Following fixed bug for me.

Resources