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.
Related
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.
So I'm currently trying to get authorization for twitter working by making use of the OAuthSwift plugin I've tried to get it working with both OAuth1 and OAuth2 both unsuccessfully and with different errors/problems.
So for OAuth2 I get this response
Whoa there!
There is no request token for this page. That's the special key we need from applications asking to use your Twitter account. Please go back to the site or application that sent you here and try again; it was probably just a mistake.
I'm using the following piece of code for this
let oauthswift = OAuth2Swift(
consumerKey: Twitter.consumerKey,
consumerSecret: Twitter.consumerSecret,
authorizeUrl: Twitter.authorizeURL,
accessTokenUrl: Twitter.accessTokenURL,
responseType: Twitter.responseType!)
let state = generateState(withLength: 20)
oauthswift.authorize(
withCallbackURL: "https://oauthswift.herokuapp.com/callback/twitter",
scope: "",
state: state,
success: { credential, response, parameters in
print("logged in with \(credential), with response \(response) and parameters \(parameters)")
},
failure: { error in
print("error occured \(error.localizedDescription)")
}
)
Then I moved on to using OAuth1 which gives me the error
Desktop applications only support the auth_callback value 'oob' while I'm obviously trying to do this from an iOS application.
the code I used here is as follows
let oauthTwitter = OAuth1Swift(
consumerKey: "myKey",
consumerSecret: "mySecret",
requestTokenUrl: "https://api.twitter.com/oauth/request_token",
authorizeUrl: "https://api.twitter.com/oauth/authorize",
accessTokenUrl: "https://api.twitter.com/oauth/access_token")
oauthswift.authorize(
withCallbackURL: "https://oauthswift.herokuapp.com/callback/twitter",
scope: "",
state: state,
success: { credential, response, parameters in
print("logged in with \(credential), with response \(response) and parameters \(parameters)")
},
failure: { error in
print("error occured \(error.localizedDescription)")
}
)
I'm hoping someone is able to tell me what I'm doing wrong here because I can't seem to figure it out.
The problem ended up to be that I had setup the wrong url scheme. It contained a _ which isn't allowed.
In my case I didn't set a callback URL for the app on Twitter Dev site - https://developer.twitter.com/en/apps
I've got and tried a number of samples using ADALiOS. ADALiOS keeps changing its implementation as you know. Because I am a beginner of swift, I don't have any idea how to make samples from Internet work.
I tried a version of adal 3.0 (pre release).
as you can see, the below code was copied from one of samples downloaded. Every sample has got a complier errors such as 'missing argument label-policy...' or 'cannot convert ADAuthenticationResult...' in authContext.acquireToken() or acquireTokenwithResource() method regardless of its adal version. anyone can help me?
the error message is about completionBlock:....
thanks
authContext.acquireToken(withScopes: [Any](), additionalScopes: [Any](), clientId: clientId, redirectUri: redirectURL, identifier: id!, promptBehavior: prompt, extraQueryParameters: "", completionBlock: <#T##ADAuthenticationCallback!##ADAuthenticationCallback!##(ADAuthenticationResult?) -> Void#>){
if result.status.value != AD_SUCCEEDED.value {
// Failed, return error description
completionHandler(false, result.error.description)
}
else {
// Succeeded, return the acess token
var token = result.accessToken
// Initialize the dependency resolver with the logged on context.
// The dependency resolver is passed to the Outlook library.
self.dependencyResolver = ADALDependencyResolver(context: authContext, resourceId: self.outlookResource, clientId: self.clientId, redirectUri: self.redirectURL)
completionHandler(true, token)
}
}
I just got this working using adal 3.0 (pre release). Looks like ADAL API has changed when looking at the examples. I couldn't find acquireTokenwithResource() so I used:
acquireToken(withScopes: additionalScopes: clientId: redirectUri: identifier:, promptBehavior:)
I think the biggest issue I had was not registering the native app here: https://apps.dev.microsoft.com
After I did that and used clientId and redirectURI from apps.dev.microsoft, and also include the correct scope, I was able to authenticate and get back an accessToken.
My acquireToken Looks like this:
func acquireAuthToken(completion: ((AuthenticationResult) -> Void)?) {
let identity = ADUserIdentifier(id: "Default email address", type: ADUserIdentifierType(rawValue:1))
self.context.acquireToken(withScopes: ["User.Read"], additionalScopes: nil, clientId: AppData.sharedInstance?.clientId, redirectUri: URL(string: (AppData.sharedInstance?.redirectUriString)!), identifier: identity, promptBehavior: AD_PROMPT_AUTO) {
(result) in
if let handler = completion {
if result!.status == AD_SUCCEEDED {
self.accessToken = result!.token
handler(AuthenticationResult.Success)
}
else {
handler(AuthenticationResult.Failure(result!.error))
}
}
}
}
The context is just ADAuthenticationContext(authority: ppData.sharedInstance?.authority, .Authority, error: &error)
HTH
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.
I'm new in programming in swift. I'm trying to read Facebook pages posts(wall) from a public page and show the content(images and messages) in my app without users login. I've already set up the app with Facebook SDK (plist, bridging-Header.h etc...). I know I must open a session and pass a valid access token to the Facebook server. But I can't understand how....
below my viewDidLoad
let request = "/(pageID)?fields=id,posts"
FBRequestConnection.startWithGraphPath(request, completionHandler: {(connection: FBRequestConnection!, result: AnyObject!, error: NSError!) -> Void in
if (error? != nil){
NSLog("error = \(error)")
}else{
println(result)
}
} as FBRequestHandler)
I get this error:
An open FBSession must be specified for calls to this endpoint.
com.facebook.sdk:ParsedJSONResponseKey={
body = {
error = {
code = 104;
message = "An access token is required to request this resource.";
type = OAuthException;
};
};
code = 400;
}}
i think i need to open a session in AppDelegate and so I can make the request I've also read the Facebook documentation but I haven't found the answer.
Please help me. Thank you!!!