2013-03-25 49 views
7

LinkedIn MVC4應用程序允許使用LinkedIn帳號登錄。我想從已登錄的用戶的linkedIn中提取所有可用的詳細信息。目前我做了以下。LinkedIn MVC4

在我AuthConfig.cs,

Dictionary<string, object> linkedInExtraData = new Dictionary<string, object>();   
     linkedInExtraData.Add("Icon", "../Images/linkedIn.png");   
     OAuthWebSecurity.RegisterClient(
      client: new App_Start.LinkedInCustomClient("xxxxxxxxxxxx", "yyyyyyyyyyyyyyy"), 
      displayName: "LinkedIn", 
      extraData: linkedInExtraData); 

在linkedInCustomClient.cs,從LinkedIn開發工具包

public class LinkedInCustomClient : OAuthClient 
{ 
    private static XDocument LoadXDocumentFromStream(Stream stream) 
    { 
     var settings = new XmlReaderSettings 
     { 
      MaxCharactersInDocument = 65536L 
     }; 
     return XDocument.Load(XmlReader.Create(stream, settings)); 
    } 


    /// Describes the OAuth service provider endpoints for LinkedIn. 
    private static readonly ServiceProviderDescription LinkedInServiceDescription = 
      new ServiceProviderDescription 
      { 
       AccessTokenEndpoint = 
         new MessageReceivingEndpoint("https://api.linkedin.com/uas/oauth/accessToken", 
         HttpDeliveryMethods.PostRequest), 
       RequestTokenEndpoint = 
         new MessageReceivingEndpoint("https://api.linkedin.com/uas/oauth/requestToken?scope=r_fullprofile", 
         HttpDeliveryMethods.PostRequest), 
       UserAuthorizationEndpoint = 
         new MessageReceivingEndpoint("https://www.linkedin.com/uas/oauth/authorize", 
         HttpDeliveryMethods.PostRequest), 
       TamperProtectionElements = 
         new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() }, 
       ProtocolVersion = ProtocolVersion.V10a 
      }; 

    public LinkedInCustomClient(string consumerKey, string consumerSecret) : 
     base("linkedIn", LinkedInServiceDescription, consumerKey, consumerSecret) { } 

    /// Check if authentication succeeded after user is redirected back from the service provider. 
    /// The response token returned from service provider authentication result. 
    [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", 
     Justification = "We don't care if the request fails.")] 
    protected override AuthenticationResult VerifyAuthenticationCore(AuthorizedTokenResponse response) 
    { 
     // See here for Field Selectors API http://developer.linkedin.com/docs/DOC-1014 
     const string profileRequestUrl = 
      "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,interests,headline,industry,summary,email-address,location:(name),picture-url,positions,associations,languages,honors,educations,date-of-birth,primary-twitter-account,three-current-positions,three-past-positions,group-memberships,specialties,skills)"; 


     string accessToken = response.AccessToken; 
     string tokenSecret = (response as ITokenSecretContainingMessage).TokenSecret; 
     string Verifier = response.ExtraData.Values.First(); 


     var profileEndpoint = 
      new MessageReceivingEndpoint(profileRequestUrl, HttpDeliveryMethods.GetRequest); 
     HttpWebRequest request = 
      WebWorker.PrepareAuthorizedRequest(profileEndpoint, accessToken); 

     try 
     { 
      using (WebResponse profileResponse = request.GetResponse()) 
      { 
       using (Stream responseStream = profileResponse.GetResponseStream()) 
       { 
        XDocument document = LoadXDocumentFromStream(responseStream); 

        return new AuthenticationResult(
         isSuccessful: true, 
         provider: ProviderName, 
         providerUserId: userId, 
         userName: userName, 
         extraData: extraData); 
       } 
      } 
     } 
     catch (Exception exception) 
     { 
      return new AuthenticationResult(exception); 
     } 
    } 

} 

在我的控制器,

AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl })); 
     if (!result.IsSuccessful) 
     { 
      return RedirectToAction("ExternalLoginFailure"); 
     } 

我需要得到以下我的控制器中的詳細信息作爲認證結

(id,first-name,last-name,interests,headline,industry,summary,email-address,location:(name),picture-url,positions,associations,languages,honors,educations,date-of-birth,primary-twitter-account,three-current-positions,three-past-positions,group-memberships,specialties,skills) 
+0

你有這個工作的實施嗎?我搜索了互聯網,找不到任何有關如何將數據從linkedIn拖入我的應用程序的好例子。 – ledgeJumper 2014-04-08 00:27:46

回答

5

您對LinkedIn的請求的回覆將是一個xml文件。格式和字段在LinkedIn Profile Fields

提到爲了得到電子郵件領域,你需要修改你的請求令牌網址爲

RequestTokenEndpoint = new MessageReceivingEndpoint("https://api.linkedin.com/uas/oauth/requestToken?scope=r_fullprofile+r_emailaddress", HttpDeliveryMethods.PostRequest),

你可以得到的字段,如下面的代碼

XDocument document = LoadXDocumentFromStream(responseStream); 
要求

例如:對於從XML文件中獲取第一個名稱字段,

var firstName = document.Root.Element("first-name").Value; 

像語言,職位,技能等字段將作爲結構化對象作爲配置文件的一部分返回。

例如:語言字段。

var Lang = document.Root.Element("languages");       
    var languages = new List<string>(); 
    if (Lang != null) 
    { 
    foreach (var l in Lang.Elements()) 
     { 
      if (l.Element("language") != null && l.Element("language").Element("name") != null) 
      { 
      languages.Add(l.Element("language").Element("name").Value); 
      } 
     } 
     } 

然後你可以添加字段到「extraData」,它可以在控制器中訪問。

extraData.Add("firstName", firstName); 
extraData.Add("languages", lang);