Not getting Profile Pic and Email address from linkedin api in MVc4 - c#

Here is my code please let me know why am not able to get emailid and profile pic.
public class LinkedInController : Controller
{
public ActionResult index()
{
return AuthenticateToLinkedIn();
}
static string token_secret = "";
public ActionResult AuthenticateToLinkedIn()
{
var credentials = new OAuthCredentials
{
CallbackUrl = "http://localhost:7326/Linkedin/callback",
ConsumerKey = ConfigurationManager.AppSettings["ConsumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["ConsumerSecret"],
Verifier = "123456",
Type = OAuthType.RequestToken
};
var client = new RestClient { Authority = "https://api.linkedin.com/uas/oauth", Credentials = credentials };
var request = new RestRequest { Path = "requestToken" };
request.AddParameter("scope", "r_emailaddress");
RestResponse response = client.Request(request);
string content = response.Conten
var contents = HttpUtility.ParseQueryString(response.Content)
var token = response.Content.Split('&')[0].Split('=')[1];
token_secret=contents["oauth_token_secret"];
Response.Redirect("https://api.linkedin.com/uas/oauth/authorize?oauth_token=" + token);
return null;
}
string token = "";
string verifier = "";
public ActionResult Callback()
{
token = Request["oauth_token"];
verifier = Request["oauth_verifier"];
var credentials = new OAuthCredentials
{
ConsumerKey = ConfigurationManager.AppSettings["ConsumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["ConsumerSecret"],
Token = token,
TokenSecret = token_secret,
Verifier = verifier,
Type = OAuthType.AccessToken,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
Version = "1.0"
};
var client = new RestClient { Authority = "https://api.linkedin.com/uas/oauth", Credentials = credentials, Method = WebMethod.Post };
var request = new RestRequest { Path = "accessToken" };
request.AddParameter("scope", "r_emailaddress");
RestResponse response = client.Request(request);
string content = response.Content;
var contents = HttpUtility.ParseQueryString(response.Content);
var accessToken =contents["oauth_token"];
var accessTokenSecret=contents["oauth_token_secret"];
var people = new LinkedInService(accessToken, accessTokenSecret).GetCurrentUser();
String companyName = people.FirstName;
return Content(companyName);
}
}
I am using Hammock and i am getting first name and last name and title and all i have enabled the r_emailadress in LinkedIn Portal but please am not able to get these information.

The only scope you're using is r_emailaddress. To get the pic, I think you need to use r_basicprofile. I can't see a field in the docs called 'emailid', only email-address.
https://developer.linkedin.com/docs/fields/basic-profile

Related

SharePoint API requests failing

I'm trying to Get all files from a folder on a SharePoint site AND creating folders on said site. So GET/POST.
When i'm trying to GET the files from the folder https://xxxxxx.sharepoint.com/sites/Test/Syra_Test/
i get a 200 success but nothing in the resulting json.: "{"odata.metadata":"https://xxxxxx.sharepoint.com/_api/$metadata#SP.ApiData.Files12\","value":[]}" i'm guessing its path issues but i don't know.
see function1()
I am now trying to create folders, however i get a 403 error.
see function2()
private static void Function1(){
//string RESTURL = "{0}/_api/web/lists/GetByTitle('Test')/items?$top=1";
string RESTURL = "{0}/_api/web/GetFolderByServerRelativeUrl('/General')/Files";
string webUrl = "https://xxxxxx.sharepoint.com";
string USER = "xxxxx#xxxxx.com";
var passWord = new SecureString();
string PWD = "xxxxx";
PWD.ToList().ForEach(passWord.AppendChar);
var credential = new SharePointOnlineCredentials(USER, passWord);
using (var handler = new HttpClientHandler() { Credentials = credential })
{
//Get authentication cookie
Uri uri = new Uri(webUrl);
handler.CookieContainer.SetCookies(uri, credential.GetAuthenticationCookie(uri));
//Invoke REST API
using (var client = new HttpClient(handler))
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync(string.Format(RESTURL, webUrl)).Result;
response.EnsureSuccessStatusCode();
string jsonData = response.Content.ReadAsStringAsync().Result;
}
}
}
private static void Function2(){
string RESTURL = "{0}/_api/web/folders";
string webUrl = "https://xxxx.sharepoint.com";
string USER = "xxxx#xxxxx.com";
var passWord = new SecureString();
string PWD = "xxxxx";
PWD.ToList().ForEach(passWord.AppendChar);
var credential = new SharePointOnlineCredentials(USER, passWord);
using (var handler = new HttpClientHandler() { Credentials = credential })
{
//Get authentication cookie
Uri uri = new Uri(webUrl);
handler.CookieContainer.SetCookies(uri, credential.GetAuthenticationCookie(uri));
//Invoke REST API
using (var client = new HttpClient(handler))
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("X-HTTP-Method", "POST");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string json = "{'__metadata': { 'type': 'SP.Folder' }, 'ServerRelativeUrl': '/shared documents/folderSyraCreated'}";
StringContent strContent = new StringContent(json);
HttpResponseMessage response = client.PostAsync(string.Format(RESTURL, webUrl), strContent).Result;
response.EnsureSuccessStatusCode();
string jsonData = response.Content.ReadAsStringAsync().Result;
}
}
}
Can't use external dll's (csom) in this case (plugin for an economy system)
Hope it makes sense :)

I want to implement sharepoint document search using C# api

I want to search sharepoint document using C# api call.
I am trying below code:
string URL = "http://server/_api/search/query?query_parameter=value&query_parameter=value";
System.Net.Http.HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "XXXXX", "XXXXXX"))));
using (client)
{
HttpResponseMessage httpResponseMessage = await client.GetAsync(URL);
HttpResponseMessage responsemMsgx = httpResponseMessage;
if (responsemMsgx.IsSuccessStatusCode)
{
}
}
But,i am have a doubt regarding URL below:
string URL = "http://server/_api/search/query?query_parameter=value&query_parameter=value";
Please help me with the sharepoint server and constructing the URL.
My expected output is something like JSON .
If you want to search documents, we can use the Search REST API below to achieve it.
/_api/search/query?querytext='IsDocument:True'
C# example:
string siteUrl = "http://sp2013/sites/team";
string searchQuery = "/_api/search/query?querytext='IsDocument:True'";//search all documents
var credential = new System.Net.NetworkCredential("username", "password", "domainname");
HttpClientHandler handler = new HttpClientHandler() { Credentials = credential };
HttpClient client = new HttpClient(handler);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
client.DefaultRequestHeaders.Add("ContentType", "application/json;odata=verbose");
var result = client.GetAsync(siteUrl+searchQuery).Result;
var content = result.Content.ReadAsStringAsync().Result;
JObject jobj = JObject.Parse(content);
JArray jarr = (JArray)jobj["d"]["query"]["PrimaryQueryResult"]["RelevantResults"]["Table"]["Rows"]["results"];
foreach (JObject j in jarr)
{
JArray results = (JArray)j["Cells"]["results"];
var title = "";
var path = "";
foreach (JObject r in results)
{
if (r["Key"] != null)
{
if (r["Key"].ToString() == "Title")
{
title = r["Value"].ToString();
}
if (r["Key"].ToString() == "Path")
{
path = r["Value"].ToString();
}
}
}
Console.WriteLine(title + "|" + path);
}

How can I get ID Token from custom token via FirebaseAdmin SDK?

How can I get ID Token from custom token?
[Fact]
public void Get_ID_Token_For_Service_Account_Test()
{
using (Stream stream = new FileStream(ServiceAccountJsonKeyFilePath, FileMode.Open, FileAccess.Read))
{
ServiceAccountCredential credential = ServiceAccountCredential.FromServiceAccountData(stream);
FirebaseApp.Create(new AppOptions
{
Credential = GoogleCredential.FromServiceAccountCredential(credential),
ServiceAccountId = ServiceAccountId,
});
var uid = "Some UID";
var additionalClaims = new Dictionary<string, object>
{
{"dmitry", "pavlov"}
};
string customToken = FirebaseAuth.DefaultInstance.CreateCustomTokenAsync(uid, additionalClaims).Result;
string idToken= null; // How to get this?
FirebaseToken token = FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(idToken, CancellationToken.None).Result;
Assert.NotNull(token);
Assert.True(token.Claims.ContainsKey("dmitry"));
}
}
I see samples for some other languages/platforms but not for C# - how to get ID token via current user here - Retrieve ID tokens on clients. But for C# neither UserRecord nor FirebaseAuth provides ID Token. Any pointers are much appreciated.
I have found the way to get the ID token in FirebaseAdmin integration tests - see method SignInWithCustomTokenAsync. The only thing I have to adjust was base URL: according to Firebase Auth REST API documentation it should be
https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken
The API KEY refers to the Web API Key, which can be obtained on the project settings page in your admin console.
So the adjusted code looks like this:
private static async Task<string> SignInWithCustomTokenAsync(string customToken)
{
string apiKey = "..."; // see above where to get it.
var rb = new Google.Apis.Requests.RequestBuilder
{
Method = Google.Apis.Http.HttpConsts.Post,
BaseUri = new Uri($"https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken")
};
rb.AddParameter(RequestParameterType.Query, "key", apiKey);
var request = rb.CreateRequest();
var jsonSerializer = Google.Apis.Json.NewtonsoftJsonSerializer.Instance;
var payload = jsonSerializer.Serialize(new SignInRequest
{
CustomToken = customToken,
ReturnSecureToken = true,
});
request.Content = new StringContent(payload, Encoding.UTF8, "application/json");
using (var client = new HttpClient())
{
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
var parsed = jsonSerializer.Deserialize<SignInResponse>(json);
return parsed.IdToken;
}
}

Authenticate user without login for web api using microsoft graph

I want to use microsoft graph in web api which is using .net core 2.0, I want to authenticate user without login prompt.
Following is the code I have used, Please correct me if my method is wrong.
string clientId = "";
string clientsecret = "";
string tenant = "";
string resourceURL = "https://graph.microsoft.com";
string userMail = "testuser3#company.com";
public async Task<string> GetMyEmailUser()
{
try
{
var result = "";
string AzureADAuthority = "https://login.microsoftonline.com/companyname.com";
AuthenticationContext authenticationContext = new AuthenticationContext(AzureADAuthority, false);
var credential = new ClientCredential(clientId, clientsecret);
var authenticationResult = authenticationContext.AcquireTokenAsync(resourceURL, credential).Result;
var token = authenticationResult.AccessToken;
using (var confClient = new HttpClient())
{
var url = "https://graph.microsoft.com/v1.0";
confClient.BaseAddress = new Uri(url);
confClient.DefaultRequestHeaders.Accept.Clear();
confClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
confClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = confClient.GetAsync(url + "/me/mailFolders/inbox/messages?$filter=isRead eq false&$top=100").Result;
var jsonString = JObject.Parse(await response.Content.ReadAsStringAsync());
IUserMessagesCollectionPage myDetails = JsonConvert.DeserializeObject<IUserMessagesCollectionPage>(jsonString["value"].ToString());
}
I am new to microsoft graph and would really appreciate your help. Thanks.

Post Photos and Videos on Facebook Wall

I need to post Photos, Videos on Facebook walls from my MVC app. I'm getting below error
(OAuthException - #2500) An active access token must be used to query information about the current user.
Please help me. Please find below code which I'm using.
string appID = string.Empty;
string appSecretCode = string.Empty;
appID = "<<application Id>>";
appSecretCode = "<<app secretcode>>";
var fb = new FacebookClient();
dynamic result = fb.Get("oauth/access_token", new
{
client_id = appID,
client_secret = appSecretCode,
grant_type = "client_credentials",
scope = "publish_stream"
});
string accessToken = result.access_token;
var client = new FacebookClient(accessToken);
var postparameters = new Dictionary<string, object>();
var media = new FacebookMediaObject
{
FileName = #"Bday.jpg",
ContentType = "image/jpeg"
};
byte[] img = System.IO.File.ReadAllBytes(#"C:\Users\user\Desktop\Bday.jpg");
media.SetValue(img);
postparameters["source"] = media;
postparameters["access_token"] = result.access_token;
var result1 = client.Post(String.Format("https://graph.facebook.com/{0}/photos", "<<User ID>>"), postparameters);
You need to generate access token from https://developers.facebook.com/tools/explorer and try:
required AcccountId, pageid
dynamic parameters = new ExpandoObject();
parameters.message =modelList.message;
parameters.subject = modelList.subject;
parameters.account_id = modelList.AcccountId;
imageBytes = byte[] of image
parameters.source = new FacebookMediaObject{
ContentType = imageType,
FileName = Url
}.SetValue(imageBytes);
client.Post(pageid+ "/photos", parameters);
Hope it will help.

Categories