Getting 403 forbidden error while accessing linkedIn 2.0 API from SharePoint 2013 web part - linkedin-api

API: https://api.linkedin.com/v2/me?projection=(id,firstName,lastName)
App Permission: r_basicprofile, r_emailaddress, w_share
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
string requesturl = "https://api.linkedin.com/v2/me?projection=(id,firstName,lastName)";
HttpWebRequest webRequest = System.Net.WebRequest.Create(requesturl) as HttpWebRequest;
webRequest.Method = "GET";
webRequest.Host = "api.linkedin.com";
//webRequest.ContentType = "application/x-www-form-urlencoded";
//webRequest.Connection = "Keep-Alive";
webRequest.Headers.Add("Authorization", "Bearer " + accessToken);
//Stream dataStream = webRequest.GetRequestStream();
//String postData = String.Empty;
//byte[] postArray = Encoding.ASCII.GetBytes(postData);
//dataStream.Write(postArray, 0, postArray.Length);
//dataStream.Close();
WebResponse response = webRequest.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(dataStream);
String returnVal = responseReader.ReadToEnd().ToString();

If you are using V2 API and you did not taken permission to use r_basicprofile then either apply for permission to use r_basicprofile to linkedin
OR use r_liteprofile + r_emailaddress for V2
(also check r_liteprofile permission is there in your app or not )
r_liteprofile for firstName,lastName,profilePicture,id
r_emailaddress for getting emailAddress
Check this : https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/migration-faq?context=linkedin/consumer/context

Related

GetResponseAsync timeout after a few POST request

i'm making a POST request in C# like this:
var request = WebRequest.Create("http://xxx.xxx.xxx.xxx:8080/xxx/obj/data/xxx/commands/GET");
request.ContentType = "application/json";
((HttpWebRequest)request).Accept = "application/json";
request.Headers.Add(HttpRequestHeader.AcceptLanguage, "en");
NetworkCredential myNetworkCredentials = new NetworkCredential("myUser", "MyPass");
CredentialCache myCredentialCache = new CredentialCache
{
{ link, "Basic", myNetworkCredentials }
};
request.Credentials = myCredentialCache;
request.PreAuthenticate = true;
request.Method = "POST";
await request.GetResponseAsync();
When i'm using Postman to check the response, it's all ok, it works every time i send the request.
But programmatically, after 7-8 times, the await request.GetResponseAsync(); is giving me a Exception, "The Operation has timed out".
I don't know how to check this, in postman it's all ok, but in the app it failed after a few test. What can i do?
By default, you have only 10 Connection Limit when you start the App. So you need to setup this in the Uri for your request
ServicePoint sp = ServicePointManager.FindServicePoint(uri);
sp.ConnectionLimit = 1000;
ServicePointManager.DefaultConnectionLimit = 1000;

PayPal API - (401) Unauthorized when requesting Access Token

I am trying to incorporate PayPal payments into our project, but I am failing at the moment hehe.
Basically, first step is to get the access token request and response, which I am trying to do with WebRequest, but it spits out 401 at me.
Following instructions from: https://developer.paypal.com/docs/integration/direct/make-your-first-call/
Here's the code:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
WebRequest request = WebRequest.Create("https://api.sandbox.paypal.com/v1/oauth2/token");
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.Credentials = new NetworkCredential("client_id", "secret");
request.PreAuthenticate = true;
string body = "grant_type=client_credentials";
byte[] buffer = Encoding.UTF8.GetBytes(body);
request.ContentLength = buffer.LongLength;
var reqStr = request.GetRequestStream();
reqStr.Write(buffer, 0, buffer.Length);
reqStr.Close();
WebResponse response = request.GetResponse();
Ofcourse, client_id and secret are replaced with real values in the code :)
Thank you for your help!
Figured it out thanks to: C# HttpWebRequest using Basic authentication
Turns out I was not using Basic Auth as intended by PayPal.
Oops :D
Hope someone finds this useful.

Service to Service Calls Using Client Credentials

I tried to create an alias for group in office 365 using below code but it shows some error.how to solve this. I tried to use service to service calls method. I got the token generated. How to check its valid or not? Is it possible to create alias using api for group without powershell option? if no kindly advice me to for other options..
string clientId = "************";
string clientsecret = "******";
string tenantId = "********";
//string resourceUri = "http://office.microsoft.com/outlook/";
string redirectUri = "https://login.live.com/oauth20_desktop.srf";
var authUri = "https://login.windows.net/" + tenantId + "/oauth2/authorize/";
var RESOURCE_URL = "https://graph.windows.net";
HttpClient client = new HttpClient();
var authContext = new AuthenticationContext(authUri);
var credential = new ClientCredential(clientId: clientId, clientSecret: clientsecret);
var result = authContext.AcquireTokenAsync(RESOURCE_URL, credential).Result;
client.DefaultRequestHeaders.Add("Authorization", "bearer " + result.AccessToken);
string content = #"{
'displayName': 'mailgrouptest',
'groupTypes': ['Unified'],
'mailEnabled': true,
'mailNickname': 'mailalias1',
'securityEnabled': false
}";
var httpContent = new StringContent(content, Encoding.GetEncoding("utf-8"), "application/json");
var response = client.PostAsync("https://graph.microsoft.com/v1.0/groups", httpContent).Result;
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
When i run this code in console it shows an error like this....is the problem with token ? or tenant id?
{
"error": {
"code": "InvalidAuthenticationToken",
"message": "Access token validation failure.",
"innerError": {``
"request-id": "*****-***-",
"date": "2016-05-25T04:53:08"
}
}
}
kindly advice me to create alias for group in api
The mailNickName of group is not able to update using the Microsoft Graph at present.
As a workaround, we can create a new group with the specific the mailNickName you wanted and use the new group. Here is the code to create a group with mailNicekName for your reference:
string clientId = "";
string clientsecret = "";
string tenant = "yourdomain.onmicrosoft.com";
var authUri = "https://login.microsoftonline.com/"+tenant+"/oauth2/token";
var RESOURCE_URL = "https://graph.microsoft.com";
HttpClient client = new HttpClient();
var authContext = new AuthenticationContext(authUri);
var credential = new ClientCredential(clientId: clientId, clientSecret: clientsecret);
var result = authContext.AcquireTokenAsync(RESOURCE_URL, credential).Result;
client.DefaultRequestHeaders.Add("Authorization", "bearer " + result.AccessToken);
string content = #"{
'description': 'description-value',
'displayName': 'displayName-value',
'groupTypes': [
'Unified'
],
'mailEnabled': true,
'mailNickname': 'mailNickname-value',
'securityEnabled': false
}";
var httpContent = new StringContent(content, Encoding.GetEncoding("utf-8"), "application/json");
//var response = client.GetAsync("https://graph.microsoft.com/v1.0/groups").Result;
var response = client.PostAsync("https://graph.microsoft.com/v1.0/groups",httpContent).Result;
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
More detail about Goupr REST API, please refer to here.
For the error “InvalidAuthenticationToken” you were request the access token with incorrect resource. To use the Microsoft Graph API, we need to specify the resource with “https://graph.microsoft.com” instead of “https://graph.windows.net”.
In addition, if you want the mailNickName of group is updateable, you can try to submit the feedback from here.

Getting 500 error while creating vertex using Rest API

I am writing a SSIS script component for importing data into orientdb using RestAPI but i am getting error 500. Please i am stuck here. Is there anyone who can help me with this. I am using version 2.1.7 community edition.
Here is my code so far.
Uri address = new Uri("http://localhost:2480//command/SQ-DB/sql/");
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
request.Method = "POST";
request.Accept = "application/json; charset=UTF-8";
request.ContentType = "application/json";
string username = "root";
string password = "***";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
request.Headers.Add("Authorization", "Basic " + encoded);
StringBuilder data = new StringBuilder();
// string link = "{\"statements\" : [ {\"statement\" : \"CREATE ( company: Accounts { Name:" + Row.companyname + "} ) RETURN company\"} ]}";
string link= "CREATE VERTEX Contacts CONTENT { 'name' : "+ Row.fullname+", 'Email' : "+ Row.emailaddress1+", 'Phone' : "+ Row.telephone1 + ", 'ContactId' : "+ Row.contactid+", 'City' : "+Row.address1city+"}" ;
data.Append(HttpUtility.UrlEncode(link));
// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
// Set the content length in the request headers
request.ContentLength = byteData.Length;
request.Headers.Add("Accept-Encoding", "gzip,deflate");
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
Console.WriteLine(reader.ReadToEnd());
}
It will be a great help if anyone can point the issue. Thank you

Post to Facebook Page from Facebook App

I want to post from my Facebook app to one of my pages using app_id and app_secret. It will help me to post directly without log in to Facebook.
I'm able to post on my profile, but not on my page!
Here is my code:
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&client_secret={1}&grant_type={2}",
app_id, app_secret, "client_credentials");
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
//meh.aspx?token1=steve&token2=jake&...
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
string access_token = tokens["access_token"];
var client = new FacebookClient(access_token);
client.Post("/my-page-FB-ID/feed", new { desctiption = description, picture = picture, link = link, caption = caption, type = type });