在MVC4使用DotNetOpenAuth LinkedIn完整的个人资料信息 [英] LinkedIn full profile details using DotNetOpenAuth in MVC4
问题描述
我MVC4应用程序允许使用的登录帐户LinkedIn。我想拉是avaible从LinkedIn的登录用户的所有细节。目前,我已经做了以下。
在我的AuthConfig.cs,
词典<字符串对象> linkedInExtraData =新词典<字符串对象>();
linkedInExtraData.Add(图标,../Images/linkedIn.png);
OAuthWebSecurity.RegisterClient(
客户端:新App_Start.LinkedInCustomClient(XXXXXXXXXXXX,yyyyyyyyyyyyyyy),
显示名:LinkedIn,
extraData:linkedInExtraData);
在linkedInCustomClient.cs,从LinkedIn开发工具包
公共类LinkedInCustomClient:OAuthClient
{
私有静态的XDocument LoadXDocumentFromStream(流流)
{
VAR设置=新XmlReaderSettings
{
MaxCharactersInDocument = 65536L
};
返回XDocument.Load(XmlReader.Create(流设置));
}
///描述了LinkedIn的OAuth的服务提供者端点。
私人静态只读ServiceProviderDescription LinkedInServiceDescription =
新ServiceProviderDescription
{
AccessTokenEndpoint =
新MessageReceivingEndpoint(https://api.linkedin.com/uas/oauth/accessToken
HttpDeliveryMethods.PostRequest)
RequestTokenEndpoint =
新MessageReceivingEndpoint(https://api.linkedin.com/uas/oauth/requestToken?scope=r_fullprofile
HttpDeliveryMethods.PostRequest)
UserAuthorizationEndpoint =
新MessageReceivingEndpoint(https://www.linkedin.com/uas/oauth/authorize
HttpDeliveryMethods.PostRequest)
TamperProtectionElements =
新ITamperProtectionChannelBindingElement [] {新HmacSha1SigningBindingElement()},
ProtocolVersion = ProtocolVersion.V10a
}; 公共LinkedInCustomClient(字符串consumerKey,串consumerSecret):
基地(LinkedIn,LinkedInServiceDescription,consumerKey,consumerSecret){} ///检查用户重定向从服务提供商回来后验证成功。
///从服务供应商认证结果返回的响应令牌。
【超级pressMessage(Microsoft.Design,CA1031:DoNotCatchGeneralExceptionTypes
理由=我们不如果请求失败无所谓了。)
保护覆盖AuthenticationResult VerifyAuthenticationCore(AuthorizedTokenResponse响应)
{
//在这里看到现场选择器API http://developer.linkedin.com/docs/DOC-1014
常量字符串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)\";
字符串的accessToken = response.AccessToken;
字符串tokenSecret =(响应,ITokenSecretContainingMessage).TokenSecret;
字符串验证= response.ExtraData.Values.First();
VAR profileEndpoint =
新MessageReceivingEndpoint(profileRequestUrl,HttpDeliveryMethods.GetRequest);
HttpWebRequest的要求=
WebWorker prepareAuthorizedRequest(profileEndpoint,的accessToken)。 尝试
{
使用(WebResponse类profileResponse = request.GetResponse())
{
使用(流responseStream = profileResponse.GetResponseStream())
{
的XDocument文档= LoadXDocumentFromStream(responseStream); 返回新AuthenticationResult(
isSuccessful:真实,
供应商:的ProviderName,
providerUserId:用户ID
用户名:用户名,
extraData:extraData);
}
}
}
赶上(例外的例外)
{
返回新AuthenticationResult(例外);
}
}}
在我的控制器,
AuthenticationResult结果= OAuthWebSecurity.VerifyAuthentication(Url.Action(ExternalLoginCallback,新的{RETURNURL = RETURNURL}));
如果(!result.IsSuccessful)
{
返回RedirectToAction(ExternalLoginFailure);
}
我需要在我的控制器作为认证结果以下细节。
<$p$p><$c$c>(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)从LinkedIn您的请求的响应将是一个XML文件。格式和字段 LinkedIn被提及的个人资料字段
有关获取电子邮件域,您需要修改请求令牌网址
RequestTokenEndpoint =新MessageReceivingEndpoint(\"https://api.linkedin.com/uas/oauth/requestToken?scope=r_fullprofile+r_emailaddress\",
HttpDeliveryMethods.PostRequest)
您可以得到场如以下code要求
的XDocument文档= LoadXDocumentFromStream(responseStream);
例如:对于从XML文件中获取第一个名称字段,
VAR的firstName = document.Root.Element(直呼其名)值。
字段,如语言,岗位,技能等将返回为目标的结构作为配置文件的一部分。
例如:语言领域
VAR LANG = document.Root.Element(语言);
VAR语言=新的List&LT;串GT;();
如果(郎!= NULL)
{
的foreach(VAR升的Lang.Elements())
{
如果(l.Element(语言)= NULL和放大器;!&安培;!l.Element(语言)元素(名称)= NULL)
{
languages.Add(l.Element(语言)元素(name)的价值。);
}
}
}
然后你就可以添加可在控制器访问字段extraData。
extraData.Add(名字,名字);
extraData.Add(语言,郎);
My MVC4 application allows login using LinkedIn account. I want to pull all details that are avaible from linkedIn of the logged in User. Currently i have done the following.
In My 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);
In linkedInCustomClient.cs , from LinkedIn Developer Kit
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);
}
}
}
In my controller,
AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
if (!result.IsSuccessful)
{
return RedirectToAction("ExternalLoginFailure");
}
I need to get the following details in my controller as authentication result.
(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)
The response of your request from LinkedIn will be a xml file. The format and fields are mentioned in LinkedIn Profile Fields
For getting email field, you need to modify your request token url as
RequestTokenEndpoint = new MessageReceivingEndpoint("https://api.linkedin.com/uas/oauth/requestToken?scope=r_fullprofile+r_emailaddress",
HttpDeliveryMethods.PostRequest),
You can get the fields as required in the following code
XDocument document = LoadXDocumentFromStream(responseStream);
Eg : For getting the first name field from the xml file,
var firstName = document.Root.Element("first-name").Value;
Fields like languages, positions, skills etc will be returned as structured objects as part of the profile.
Eg : Language field.
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);
}
}
}
Then you can add fields to "extraData" which can be accessed in the controller.
extraData.Add("firstName", firstName);
extraData.Add("languages", lang);
这篇关于在MVC4使用DotNetOpenAuth LinkedIn完整的个人资料信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!