我正在使用ASP.NET Core 2.1,并且想使用LinkedIn身份验证。
因为默认情况下没有扩展方法.AddLinkedIn
(由Microsoft开发人员开发),所以我尝试了:
services.AddOAuth("LinkedIn", options =>
{
options.ClientId = Configuration["Authentication:LinkedIn:ClientId"];
options.ClientSecret = Configuration["Authentication:LinkedIn:ClientSecret"];
options.Scope.Add("r_basicprofile");
options.Scope.Add("r_emailaddress");
options.CallbackPath = "/signin-linkedin";
options.AuthorizationEndpoint = "https://www.linkedin.com/oauth/v2/authorization";
options.TokenEndpoint = "https://www.linkedin.com/oauth/v2/accessToken";
options.UserInformationEndpoint = "https://api.linkedin.com/v1/people/~:(id,formatted-name,email-address,picture-url)";
options.Events = new OAuthEvents
{
OnCreatingTicket = async context =>
{
using (var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint))
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);
request.Headers.Add("x-li-format", "json");
var response = await context.Backchannel.SendAsync(request, context.HttpContext.RequestAborted);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
string responseText = await response.Content.ReadAsStringAsync();
var user = Newtonsoft.Json.Linq.JObject.Parse(responseText);
context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Value<string>("id")));
context.Identity.AddClaim(new Claim(ClaimTypes.Name, user.Value<string>("formattedName")));
context.Identity.AddClaim(new Claim(ClaimTypes.Email, user.Value<string>("emailAddress")));
context.Identity.AddClaim(new Claim("picture", user.Value<string>("pictureUrl")));
}
}
}
};
});
在控制器中,我尝试获取信息:
var info = await _signInManager.GetExternalLoginInfoAsync();
它返回null。
我试图清除所有cookie,然后再次使用Facebook,Google或Twitter等其他服务登录。除了LinkedIn之外,所有其他人都工作正常(我得到了信息)。为什么?
答案 0 :(得分:0)
我试图重写代码并更改行:
using (var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint))
到
var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
然后,它应该可以工作! (我不知道为什么)。
在此操作期间,似乎无法接受using
块。关闭范围后,所有索赔将被清除。