Login With LinkedIn on Xamarin.Android

137 views
Skip to first unread message

exosk...@gmail.com

unread,
Dec 17, 2016, 10:19:19 AM12/17/16
to back{4}app
Hello, im trying to create a way to login with linkedin and create or login the parse.com user.
This is what i have try so far but im getting, invalid parse session token (authentication works, the oriblem occurs with parse.com):

void LoginToLinkedIn()
       
{
           
var auth = new OAuth2Authenticator(
                clientId
: "**",
                clientSecret
: "**",
                scope
: "r_basicprofile r_emailaddress",
                authorizeUrl
: new Uri("https://www.linkedin.com/oauth/v2/authorization"),
                redirectUrl
: new Uri("https://www.linkedin.com/auth/callback"),
                accessTokenUrl
: new Uri("https://www.linkedin.com/oauth/v2/accessToken")
           
);


           
// If authorization succeeds or is canceled, .Completed will be fired.
            auth
.AllowCancel = true;
            auth
.ShowUIErrors = false;
           
//auth.Error += (sender, e) => auth.OnCancelled();
            auth
.Completed += async (sender, eventArgs) => {
           
if (!eventArgs.IsAuthenticated)
           
{
                   
System.Console.Out.WriteLine("Authentication error");
                   
return;
           
}
                   
else
                   
{
                   
System.Console.Out.WriteLine("Authentication Succeded");
                   
string dd = eventArgs.Account.Username;
                   
var values = eventArgs.Account.Properties;
                   
foreach (KeyValuePair<string, string> temp in values)
                   
{
                       
System.Console.Out.WriteLine("eventArgs.Account.Properties: Temp.Key: {0}, Temp.Value: {1}", temp.Key, temp.Value);
                   
}
                   
var access_token = values["access_token"];
                       
var request = HttpWebRequest.Create(string.Format(@"https://api.linkedin.com/v1/people/~:(id,firstName,lastName,picture-url)?format=json&oauth2_access_token=" + access_token, ""));
                        request
.ContentType = "application/json";
                        request
.Method = "GET";


                       
using (HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse)
                       
{
                           
System.Console.Out.WriteLine("Entered, Stautus Code is: {0}", response.StatusCode);


                           
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                           
{
                               
var content = reader.ReadToEnd();
                               
if (!string.IsNullOrWhiteSpace(content))
                               
{


                                   
System.Console.Out.WriteLine(content);
                               
}
                           
var result = JsonConvert.DeserializeObject<Dictionary<string,string>>(content);
                           
var userID = result["id"];
                           
var name = result["firstName"] + " " + result["lastName"];
                            application
.currentUserName = name;


                           
var _access_token = eventArgs.Account.Properties["access_token"];
                           
Java.Net.URL myUri = new Java.Net.URL(result["pictureUrl"]);
                            imageUrl
= myUri;
                            realName
= name;


                           
var authData = new Dictionary<string, string>();
                            authData
.Add("user_id", userID.ToString());
                            authData
.Add("screen_name", name.ToString());
                            authData
.Add("oauth_token", _access_token.ToString());
                            await
ParseLoginOrCreateLinkedIn(authData);
                       
}
                       
}
               
}
           
};


           
var ui = auth.GetUI(this);
           
StartActivity(ui);
       
}




public async Task<ParseUser> ParseLoginOrCreateLinkedIn(Dictionary<string, string> authInfo)
       
{
           
var rest = new RestSharp.RestClient("https://api.parse.com");
           
var req = new RestSharp.RestRequest("1/users/", RestSharp.Method.POST);
            req
.AddHeader("X-Parse-Application-Id", "nDGlfLgW2Ml2AV9jgFOiNVE1sCstKrvVaOOVyGkM");
            req
.AddHeader("X-Parse-REST-API-Key", "J1YIQXRZ8JeyKEquXGffuTq5JhKjxDtEmMM2ggb4");
            req
.AddHeader("Content-Type", "application/json");


           
var payload = "{ \"authData\": { \"linkedin\": { ";
            payload
+= "\"id\": \"" + authInfo["user_id"] + "\", ";
            payload
+= "\"screen_name\": \"" + authInfo["screen_name"] + "\", ";
            payload
+= "\"auth_token\": \"" + authInfo["oauth_token"] + "\", ";
            payload
+= "} } }";


            req
.AddParameter("application/json", payload, RestSharp.ParameterType.RequestBody);


           
RestSharp.IRestResponse res = null;
           
var result = await Task<JContainer>.Run(() =>
           
{
                res
= rest.Execute(req);
               
var content = res.Content;
               
return JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JContainer>(content);
           
});
           
var sessionToken = (String)result["sessionToken"];
           
var objectId = (String)result["objectId"];


           
if (res.StatusCode == System.Net.HttpStatusCode.Created)
           
{
                req
= new RestSharp.RestRequest("1/users/" + objectId, RestSharp.Method.PUT);
                req
.AddHeader("X-Parse-Application-Id", "nDGlfLgW2Ml2AV9jgFOiNVE1sCstKrvVaOOVyGkM");
                req
.AddHeader("X-Parse-REST-API-Key", "J1YIQXRZ8JeyKEquXGffuTq5JhKjxDtEmMM2ggb4");
                req
.AddHeader("X-Parse-Session-Token", sessionToken);
                req
.AddHeader("Content-Type", "application/json");


                req
.AddParameter("application/json", "{ \"username\": \"" + authInfo["screen_name"] + "\" }", RestSharp.ParameterType.RequestBody);
                result
= await Task<JContainer>.Run(() =>
               
{
                    res
= rest.Execute(req);
                   
var content = res.Content;
                   
return JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JContainer>(content);
               
});
           
}


            await
ParseUser.BecomeAsync(sessionToken);


           
if (ParseUser.CurrentUser.ContainsKey("Name"))
               
ParseUser.CurrentUser["Name"] = realName;
           
else
               
ParseUser.CurrentUser.Add("Name", realName);
            application
.currentUserName = realName;
           
var webClient = new WebClient();
           
byte[] bytes = null;
            application
.currentUserImageUrl = imageUrl.ToString();
            bytes
= await webClient.DownloadDataTaskAsync(imageUrl.ToString());
           
ParseFile saveImageFile = new ParseFile("profileImage.jpg", bytes);
           
if (ParseUser.CurrentUser.ContainsKey("profile_pic"))
               
ParseUser.CurrentUser["profile_pic"] = saveImageFile;
           
else
               
ParseUser.CurrentUser.Add("profile_pic", saveImageFile);
            application
.currentUser = ParseUser.CurrentUser;
            await
ParseUser.CurrentUser.SaveAsync();
           
DisplayLoadingMessage(false);
           
ChangeScreen();


           
return ParseUser.CurrentUser;
       
}

exosk...@gmail.com

unread,
Dec 17, 2016, 10:34:16 AM12/17/16
to back{4}app
im seeing here: https://parseplatform.github.io/docs/rest/guide/ that for logging in we need

curl -X POST \ -H "X-Parse-Application-Id: ${APPLICATION_ID}" \ -H "X-Parse-REST-API-Key: ${REST_API_KEY}" \ -H "X-Parse-Revocable-Session: 1" \ -H "Content-Type: application/json" \ -d '{ "authData": { "twitter": { "id": "12345678", "screen_name": "ParseIt", "consumer_key": "SaMpLeId3X7eLjjLgWEw", "consumer_secret": "SaMpLew55QbMR0vTdtOACfPXa5UdO2THX1JrxZ9s3c", "auth_token": "12345678-SaMpLeTuo3m2avZxh5cjJmIrAfx4ZYyamdofM7IjU", "auth_token_secret": "SaMpLeEb13SpRzQ4DAIzutEkCE2LBIm2ZQDsP3WUU" } } }' \ https://api.parse.com/1/users

but LinkedIn doesnt give me consumer_key, consumer_secret and auth_token_secret

casag...@back4app.com

unread,
Jan 20, 2017, 7:44:25 AM1/20/17
to back{4}app
Hello!

If you've already migrated to us, you'll need to change the URLs of your code and POST request to:

https://parseapi.back4app.com/<your_Class_Name>

and removing the "/1" from your class paths.

Let me know if that helped.

Best!

exosk...@gmail.com

unread,
Jan 20, 2017, 8:18:21 AM1/20/17
to back{4}app
Hello, what do you mean by yourClassName?

casag...@back4app.com

unread,
Jan 20, 2017, 8:56:24 AM1/20/17
to back{4}app
From the code and the POST request that you've sent you were trying to reach "users". Is that a class of yours?

If it's not you can use the same link that I sent you but using the function you want to call in the POST instead: 

https://parseapi.back4app.com/<your_Function>

Best!
Reply all
Reply to author
Forward
0 new messages