Andrei Dobrin Andrei Dobrin - 1 year ago 88
ASP.NET (C#) Question

How to get LinkedIn user skills, education and positions without OAuth

I am developing an ASP.NET Core application in which the user MUST use individual database accounts. In all the tutorials it is clearly stated that I must select "No Authentication" when I create the project. I do not understand why.

I want to let the user to be able to log-in with LinkedIn and then get their mail, name and other information. I can get that with:

app.UseLinkedInAuthentication(AuthenticationSettings.LinkedInOptions(
Configuration["LinkedIn:ClientId"],
Configuration["LinkedIn:ClientSecret"]));


in Startup.cs and (plus all other steps in the documentation)

var loginProviders = SignInManager.GetExternalAuthenticationSchemes().ToList();
if (loginProviders.Count == 0)
{
<div>
<p>
There are no external authentication services configured. See <a href="https://go.microsoft.com/fwlink/?LinkID=532715">this article</a>
for details on setting up this ASP.NET application to support logging in via external services.
</p>
</div>
}
else
{
<form asp-controller="Account" asp-action="ExternalLogin" asp-route-returnurl="@ViewData["ReturnUrl"]" method="post" class="form-horizontal">
<div>
<p>
@foreach (var provider in loginProviders)
{
<button type="submit" class="btn btn-default" name="provider" value="@provider.AuthenticationScheme" title="Log in using your @provider.DisplayName account">@provider.AuthenticationScheme</button>
}
</p>
</div>
</form>
}


In _Layout.cshtml:

I get the button, the user is asked to grant permission to the app and I get the personal data, but how can I get the other information (skills, educations, positions, etc) like in:

How to Retrieve all possible information about a LinkedIn Account ? (API using C#)

but without OAuth or how can I implement OAuth with Authorization selected when creating the project?

Answer Source

I am using individual database accounts, and this is how i make it work:

In Startup.cs

app.UseLinkedInAuthentication(AuthenticationSettings.LinkedInOptions(

                Configuration["LinkedIn:ClientId"],
                Configuration["LinkedIn:ClientSecret"]

Create a class AuthentificationSettings like this one:

public class AuthenticationSettings
    {
      public static LinkedInAuthenticationOptions LinkedInOptions(string clientId, string clientSecret)
        {

            if (string.IsNullOrEmpty(clientId))
            {
                throw new ArgumentNullException($"{nameof(clientId)} is null or empty");
            }

            if (string.IsNullOrEmpty(clientSecret))
            {
                throw new ArgumentNullException($"{nameof(clientSecret)} is null or empty");
            }

            LinkedInAuthenticationOptions options = new LinkedInAuthenticationOptions
            {

                ClientId = clientId,
                ClientSecret = clientSecret,
                SaveTokens = true,
                Events = new OAuthEvents
                {
                    OnCreatingTicket = async ctx =>
                    {
                        ctx.Identity.AddClaim(new Claim("access_token", ctx.AccessToken));
                        ctx.Identity.AddClaim(new Claim("refresh_token", ctx.AccessToken));
                        ctx.Identity.AddClaim(new Claim("ExpiresIn", ctx.ExpiresIn.Value.Seconds.ToString()));


                        // request is the GET request for linkedin

                        var request = new HttpRequestMessage(HttpMethod.Get, "https://api.linkedin.com/v1/people/~:(first-name,last-name,headline,picture-url,industry,summary,positions:(title,summary,start-date,end-date,company:(name,industry)))   ");

                        request.Headers.Authorization =new AuthenticationHeaderValue("Bearer", ctx.AccessToken);
                        request.Headers.Add("x-li-format", "json");

                        var response = await ctx.Backchannel.SendAsync(request, ctx.HttpContext.RequestAborted);
                        response.EnsureSuccessStatusCode();

                        // In user is stored the profile details

                        var user = JObject.Parse(await response.Content.ReadAsStringAsync());


                        // Save the linkedin details in variabels

                        string json = user.ToString();

                        LinkedinCandidate linkedinProfile = JsonConvert.DeserializeObject<LinkedinCandidate>(json);

                        var firstName = linkedinProfile.firstName;
                        var lastName = linkedinProfile.lastName;
                        var headline = linkedinProfile.headline;
                        var pictureUrl = linkedinProfile.pictureUrl;
                        var summaryProfile = linkedinProfile.summary;

                        var summaryCOmpany = linkedinProfile.positions.values[0].summary;
                        var titleJob = linkedinProfile.positions.values[0].title;
                        var companyName = linkedinProfile.positions.values[0].company.name;
                        var industry = linkedinProfile.positions.values[0].company.industry;
                        var monthStart = linkedinProfile.positions.values[0].startDate.month;
                        var yearStart = linkedinProfile.positions.values[0].startDate.year;



                        await Task.FromResult(0);
                    },
                    OnRemoteFailure = ctx =>
                    {
                        // Handle remote errors

                        return Task.FromResult(0);
                    }
                }


            };

            return options;
        }
    }

I managed to get only a few fields to a json, and then make an object with them(I have tried to get the education and rest of the experience by giving them as parameters in the api get url, but it hasn't worked). To make the object you must make a Model Class for this json:

{  "firstName": "",  
    "headline": "",  
    "lastName": "",  
    "pictureUrl": "",  
    "positions": {    
                    "_total": 1,    
                    "values": [   {        
                                    "company": {          
                                                "industry": "",          
                                                "name": ""        },        
                                                "startDate": {          
                                                                "month": ,          
                                                                "year":         
                                                                },        
                                                "summary": "",        
                                                "title": ""      
                                                }    
                              ] 
                },  
    "summary": ""}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download