LinkedIn login with custom token ( ERROR_INVALID_CUSTOM_TOKEN ) - ios

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.

Related

linkedin get profile - Request failed: forbidden (403) error swift

I am facing problem with "https://api.linkedin.com/v2/me" api of LinkedIn. Code was working good when I was using v1 api. I have updated my code for version 2 api for linkedIn authentication and When I tried to get profile with api "https://api.linkedin.com/v2/me" I am getting error Request failed: forbidden (403). I don't know how to resolve it.
Here is my code:
let linkedinHelper = LinkedinSwiftHelper(configuration: LinkedinSwiftConfiguration(clientId: Constant.Key.kLinkedInClientId, clientSecret: Constant.Key.kLinkedInClientSecret, state: Constant.Key.kLinkedInState, permissions: ["r_basicprofile", "r_emailaddress"], redirectUrl: Constant.Key.kLinkedInRedirectURL),nativeAppChecker: WebLoginOnly())
linkedinHelper.authorizeSuccess({ (token) in
print(token)
let url = "https://api.linkedin.com/v2/me"
linkedinHelper.requestURL(url, requestType: LinkedinSwiftRequestGet, success: { (response) -> Void in
print(response)
}) {(error) -> Void in
print(error.localizedDescription)
//handle the error
}
I've set URL scheme in info.plist as well.
You have to pass key in oauth2_access_token
Example:
https://api.linkedin.com/v2/me?oauth2_access_token={linkedin_key}
Edit:-
Also in permission need to set "r_liteprofile" instead of "r_basicprofile". To change permission worked for me.

Re-using access token in Firebase 3

I have an iOS app that uses Firebase as a backend for authentication.
Once a user logs in and then closes the app, I don't want the user to have to re-enter their email and password. My approach is to save the access token after a successful login to the Keychain, and then when the user comes back to the app, use the token from the keychain to signin.
I've tried using the method FIRAuth.auth()?.signInWithCustomToken(customToken) { (user, error) in but that's not quite right as that's for when using custom tokens, which is not what I'm doing.
Is there a way for me to do this?
// login with email / password
FIRAuth.auth()?.signInWithEmail(email, password: password, completion: { (firebaseUser, error) in
if error == nil {
FIRAuth.auth()!.currentUser!.getTokenWithCompletion({ (token, error) in
if error == nil {
// save token to keychain
} else {
print(error)
}
})
} else {
print(error)
}
})
// user comes back to app
do {
// get saved token from keychain
if let myToken = try keychain.get("token") {
FIRAuth.auth()?.signInWithCustomToken(myToken, completion: { (user: FIRUser?, error: NSError?) in
if error == nil {
// show post login screen
} else {
}
})
}
} catch {
// error getting token from keychain
}
}
I was approaching this problem in the wrong way. Saving a token is appropriate when using a 3rd party authentication provider, like Facebook, Google, etc and getting an OAuth token in return from one of those services.
In my case when logging in using email and password, a token is not required and instead the password can be securely saved in the Keychain and used later for login.

Unable to get Facebook permissions after HTTPMethod DELETE in Swift

I am working on an app that logs in to Facebook using the FBSDK in Swift. I also have been able to make requests to get my wall posts by using
var request: FBSDKGraphRequest
request = FBSDKGraphRequest(graphPath: "me/feed"), parameters: ["access_token": FBSDKAccessToken.currentAccessToken().tokenString], HTTPMethod:"GET")
request.startWithCompletionHandler({(connection, result, error) -> Void in
if error != nil
{
}
else
{
}
})
but I have been unable to get back results after I used the following to log out
var deletePermission = FBSDKGraphRequest(graphPath: "me/permissions/", parameters: nil, HTTPMethod: "DELETE")
deleterPermission.startWithCompletionHandler({(connection, result, error) -> Void in
if error != nil
{
}
else
{
}
})
When I log back in to the app, I am again asked to accept permissions, but when I check the expiration date for the current token with FBSDKAccessToken.currentAccessToken().expirationDate I get a date before I tried HTTPMethod: DELETE.
So I was wondering how it would be possible to get back permission for your app or renew my access token because I don't think it's working by logging back in and accepting permissions. I have used the following to log out of the app
// Log out of the database I'm using
try! FIRAuth.auth()!.signOut()
// Log out of Facebook, clear current token and logged user
FBSDKAccessToken.setCurrentAccessToken(nil)
FBSDKProfile.setCurrentProfile(nil)
I am also using `FBSDKLoginButton()' and setting the following permissions to log in
var loginButton = FBSDKLoginButton()
loginButton.readPermissions = ["public_profile", "user_friends", "user_about_me", "user_posts"]
loginButton.delegate = self
....
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
if error == nil
{
let credential = FIRFacebookAuthProvider.credentialWithAccessToken(FBSDKAccessToken.currentAccessToken().tokenString)
// Firebase authentication
FIRAuth.auth()?.signInWithCredential(credential) {(user, error) in
if error == nil
{
// No error found get user credentials through Firebase
}
else
{
}
}}
But again after logging in and going to another ViewController by segue and I check the current token to get "me/feed" I am not getting a reply and the token's expiration date has expired. Would it be easier to create a new app in Facebook developer and set it up in Xcode or is there something I can do to get my user posts?

custom login for firebase in swift

I have to implement a chat platform using firebase and swift.
I know how to create a user using emailid :
firebase.createUser(emailTextField, password: passwordTextField.text) { (error:NSError!) -> Void in
if (error != nil){
print(error.localizedDescription)
self.displayMessage(error)
} else{
print("New user created")
self.requestUsername()
}
}
But I am not taking any email id or other accounts. I want to create a custom user. For that they have mentioned to use the secure JWT Token and then use this :
let ref = Firebase(url: "https://<YOUR-FIREBASE-APP>.firebaseio.com/")
ref.authWithCustomToken(AUTH_TOKEN, withCompletionBlock: { error, authData in
if error != nil {
println("Login failed! \(error)")
} else {
println("Login succeeded! \(authData)")
}
})
But they have not mentioned how to generate secure JWT Token in swift.
Anyone know?
Here is the link i referred:
How to login in firebase
As you probably noticed, there is no helper library from Firebase for minting custom tokens on iOS. There is however a set of instructions on how to mint tokens here: https://www.firebase.com/docs/ios/guide/login/custom.html#section-tokens-without-helpers
Minting tokens in a client-app is in general a VERY bad idea, since it requires that you have your Firebase's secret in your app, where any user can find it.

OAuth Twitter iOS Swift

I am building an application with Swift-iOS and deployd as backend Deployd. I'm trying to figure out Twitter OAuth. Basically I would want to know how can I send my server a token and let dpd-passport save it in a user collection.
Twitter API is returning access token very fine. Here's my code:
TwitterClient.SharedInstance.requestSerializer.removeAccessToken()
//where TwitterClient is a BDBOAuth1SessionManager instance
TwitterClient.SharedInstance.fetchRequestTokenWithPath("oauth/request_token", method: "GET", callbackURL: NSURL(string: "cptwitter://oauth"), scope: nil, success: { (requestToken: BDBOAuth1Credential!) -> Void in
print(requestToken.token)
let authURL = NSURL(string: "https://api.twitter.com/oauth/authorize?oauth_token=\(requestToken.token)")
UIApplication.sharedApplication().openURL(authURL!)
}) { (error: NSError!) -> Void in
print("failed to get the token request")
}

Resources