Я реализую проверку подлинности LinkedIn в моем приложении ASP.NET Core, но по какой-то причине я не получаю никаких данных из LinkedIn. Где я ошибаюсь?ASP.NET Core LinkedIn Аутентификация Не получение данных
В ConfigureServices из Startup.cs, я следующее:
services.AddMvc(options =>
{
options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()));
});
services.AddAuthentication(options =>
{
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
});
В конфиг Startup.cs, у меня есть следующий код:
app.AuthenticationForMyApp(
Configuration["linkedInClientId"],
Configuration["linkedInClientSecret"],
Configuration["linkedInCallback"]);
Мой код выглядит в AuthenticationForMyApp класс:
public static void AuthenticationForMyApp(this IApplicationBuilder app, string linkedInClientId, string linkedInSecret, string linkedInCallback)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme,
LoginPath = new PathString("/login"),
AccessDeniedPath = new PathString("/unauthorized"),
AutomaticAuthenticate = true,
AutomaticChallenge = true
});
app.UseOAuthAuthentication(new OAuthOptions()
{
AuthenticationScheme = "LinkedIn",
ClientId = linkedInClientId,
ClientSecret = linkedInSecret,
CallbackPath = linkedInCallback,
AuthorizationEndpoint = "https://www.linkedin.com/oauth/v2/authorization",
TokenEndpoint = "https://www.linkedin.com/oauth/v2/accessToken",
UserInformationEndpoint = "https://api.linkedin.com/v1/people/~:(id,formatted-name,email-address,picture-url)",
Scope = { "r_basicprofile", "r_emailaddress" },
Events = new OAuthEvents()
{
OnCreatingTicket = OnCreatingTicketLinkedInCallback,
OnTicketReceived = OnTicketReceivedCallback
}
});
}
private static Task OnCreatingTicketLinkedInCallback(OAuthCreatingTicketContext ctx)
{
var token = ctx.AccessToken;
// *** Here ctx.User has no data about the user!!!
var firstName = ctx.User["first_name"];
var lastName = ctx.User["last_name"];
var gender = ctx.User["gender"];
var email = ctx.User["email"];
var identity = ctx.Identity as ClaimsIdentity;
if (firstName != null)
{
identity.AddClaim(new Claim(ClaimTypes.GivenName, firstName.ToString(), ClaimValueTypes.String, "LinkedIn"));
}
if (lastName != null)
{
identity.AddClaim(new Claim(ClaimTypes.Surname, lastName.ToString(), ClaimValueTypes.String, "LinkedIn"));
}
if (email != null)
{
identity.AddClaim(new Claim(System.Security.Claims.ClaimTypes.Email, email.ToString(), ClaimValueTypes.String, "LinkedIn"));
}
if (gender != null)
{
identity.AddClaim(new Claim(ClaimTypes.Gender, gender.ToString(), ClaimValueTypes.String, "LinkedIn"));
}
identity.AddClaim(new Claim("linkedin.token", token));
return Task.FromResult(true);
}
private static Task OnTicketReceivedCallback(TicketReceivedContext ctx)
{
var identity = ctx.Principal.Identity as ClaimsIdentity;
if (identity == null)
{
ctx.ReturnUri = "/unauthorized";
}
else
{
if (ctx.Properties.Items.ContainsKey("returnUrl"))
{
ctx.ReturnUri += "?returnUrl=" + ctx.Properties.Items["returnUrl"];
}
}
return Task.FromResult(true);
}
Там уже пакет LinkedIn: https://github.com/aspnet-contrib/AspNet.Security.OAuth.Providers/blob/dev/src/AspNet.Security.OAuth.LinkedIn/LinkedInAuthenticationExtensions.cs – Tratcher
Спасибо для вашего предложения, но я не хочу раздувать мое приложение с помощью ненужного кода/пакетов/библиотек. Я действительно должен быть в состоянии заставить этот код работать. – Sam