asp.net-mvc-4 – LinkedIn在MVC4中使用DotNetOpenAuth的完整个人资料

前端之家收集整理的这篇文章主要介绍了asp.net-mvc-4 – LinkedIn在MVC4中使用DotNetOpenAuth的完整个人资料前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的MVC4应用程序允许使用LinkedIn帐户登录.我想从登录用户的linkedIn中提取所有可用的详细信息.目前我做了以下工作.

在My AuthConfig.cs中,

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

在LinkedIn Developer Kit中的linkedInCustomClient.cs中

  1. public class LinkedInCustomClient : OAuthClient
  2. {
  3. private static XDocument LoadXDocumentFromStream(Stream stream)
  4. {
  5. var settings = new XmlReaderSettings
  6. {
  7. MaxCharactersInDocument = 65536L
  8. };
  9. return XDocument.Load(XmlReader.Create(stream,settings));
  10. }
  11.  
  12.  
  13. /// Describes the OAuth service provider endpoints for LinkedIn.
  14. private static readonly ServiceProviderDescription LinkedInServiceDescription =
  15. new ServiceProviderDescription
  16. {
  17. AccessTokenEndpoint =
  18. new MessageReceivingEndpoint("https://api.linkedin.com/uas/oauth/accessToken",HttpDeliveryMethods.PostRequest),RequestTokenEndpoint =
  19. new MessageReceivingEndpoint("https://api.linkedin.com/uas/oauth/requestToken?scope=r_fullprofile",UserAuthorizationEndpoint =
  20. new MessageReceivingEndpoint("https://www.linkedin.com/uas/oauth/authorize",TamperProtectionElements =
  21. new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() },ProtocolVersion = ProtocolVersion.V10a
  22. };
  23.  
  24. public LinkedInCustomClient(string consumerKey,string consumerSecret) :
  25. base("linkedIn",LinkedInServiceDescription,consumerKey,consumerSecret) { }
  26.  
  27. /// Check if authentication succeeded after user is redirected back from the service provider.
  28. /// The response token returned from service provider authentication result.
  29. [SuppressMessage("Microsoft.Design","CA1031:DoNotCatchGeneralExceptionTypes",Justification = "We don't care if the request fails.")]
  30. protected override AuthenticationResult VerifyAuthenticationCore(AuthorizedTokenResponse response)
  31. {
  32. // See here for Field Selectors API http://developer.linkedin.com/docs/DOC-1014
  33. const string profileRequestUrl =
  34. "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)";
  35.  
  36.  
  37. string accessToken = response.AccessToken;
  38. string tokenSecret = (response as ITokenSecretContainingMessage).TokenSecret;
  39. string Verifier = response.ExtraData.Values.First();
  40.  
  41.  
  42. var profileEndpoint =
  43. new MessageReceivingEndpoint(profileRequestUrl,HttpDeliveryMethods.GetRequest);
  44. HttpWebRequest request =
  45. WebWorker.PrepareAuthorizedRequest(profileEndpoint,accessToken);
  46.  
  47. try
  48. {
  49. using (WebResponse profileResponse = request.GetResponse())
  50. {
  51. using (Stream responseStream = profileResponse.GetResponseStream())
  52. {
  53. XDocument document = LoadXDocumentFromStream(responseStream);
  54.  
  55. return new AuthenticationResult(
  56. isSuccessful: true,provider: ProviderName,providerUserId: userId,userName: userName,extraData: extraData);
  57. }
  58. }
  59. }
  60. catch (Exception exception)
  61. {
  62. return new AuthenticationResult(exception);
  63. }
  64. }
  65.  
  66. }

在我的控制器中,

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

我需要在控制器中获取以下详细信息作为身份验证结果.

  1. (id,skills)

解决方法

来自LinkedIn的请求的响应将是一个xml文件.格式和字段在 LinkedIn Profile Fields中提到

获取电子邮件字段,您需要将请求令牌网址修改

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

您可以按照以下代码中的要求获取字段

  1. XDocument document = LoadXDocumentFromStream(responseStream);

例如:要从xml文件获取名字字段,

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

语言,职位,技能等字段将作为结构对象返回,作为配置文件的一部分.

例如:语言领域.

  1. var Lang = document.Root.Element("languages");
  2. var languages = new List<string>();
  3. if (Lang != null)
  4. {
  5. foreach (var l in Lang.Elements())
  6. {
  7. if (l.Element("language") != null && l.Element("language").Element("name") != null)
  8. {
  9. languages.Add(l.Element("language").Element("name").Value);
  10. }
  11. }
  12. }

然后,您可以将字段添加到“extraData”,可以在控制器中访问.

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

猜你在找的asp.Net相关文章