Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Add provider for https://ok.ru
  • Loading branch information
ajupov committed Jun 8, 2018
commit 2e9eba26316e1232bf640d79ca1afd85a0522294
7 changes: 7 additions & 0 deletions AspNet.Security.OAuth.Providers.sln
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AspNet.Security.OAuth.Patre
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AspNet.Security.OAuth.QQ", "src\AspNet.Security.OAuth.QQ\AspNet.Security.OAuth.QQ.csproj", "{7C2E82CE-F6EC-41A8-AA22-3466505F95D8}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AspNet.Security.OAuth.Odnoklassniki", "src\AspNet.Security.OAuth.Odnoklassniki\AspNet.Security.OAuth.Odnoklassniki.csproj", "{A7A947E0-D974-4E14-8904-5AAFC0AE99C1}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -304,6 +306,10 @@ Global
{7C2E82CE-F6EC-41A8-AA22-3466505F95D8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7C2E82CE-F6EC-41A8-AA22-3466505F95D8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7C2E82CE-F6EC-41A8-AA22-3466505F95D8}.Release|Any CPU.Build.0 = Release|Any CPU
{A7A947E0-D974-4E14-8904-5AAFC0AE99C1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A7A947E0-D974-4E14-8904-5AAFC0AE99C1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A7A947E0-D974-4E14-8904-5AAFC0AE99C1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A7A947E0-D974-4E14-8904-5AAFC0AE99C1}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -356,6 +362,7 @@ Global
{86614CB9-0768-40BF-8C27-699E3990B733} = {C1352FD3-AE8B-43EE-B45B-F6E0B3FBAC6D}
{ED8A220C-45FE-45C6-9B8F-BB009ACE972E} = {C1352FD3-AE8B-43EE-B45B-F6E0B3FBAC6D}
{7C2E82CE-F6EC-41A8-AA22-3466505F95D8} = {C1352FD3-AE8B-43EE-B45B-F6E0B3FBAC6D}
{A7A947E0-D974-4E14-8904-5AAFC0AE99C1} = {C1352FD3-AE8B-43EE-B45B-F6E0B3FBAC6D}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {C7B54DE2-6407-4802-AD9C-CE54BF414C8C}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">

<Import Project="..\..\build\packages.props" />

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>

<PropertyGroup>
<Description>ASP.NET Core security middleware enabling Odnoklassniki authentication.</Description>
<Authors>Usman Ajupov</Authors>
<PackageTags>aspnetcore;authentication;odnoklassniki;oauth;security</PackageTags>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="JetBrains.Annotations" Version="$(JetBrainsVersion)" PrivateAssets="All" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.OAuth" Version="$(AspNetCoreVersion)" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/aspnet-contrib/AspNet.Security.OAuth.Providers
* for more information concerning the license and the contributors participating to this project.
*/

namespace AspNet.Security.OAuth.Odnoklassniki
{
/// <summary>
/// Contains constants specific to the <see cref="OdnoklassnikiAuthenticationHandler"/>.
/// </summary>
public static class OdnoklassnikiAuthenticationConstants
{
public static class Claims
{
public const string Pic1 = "urn:odnoklassniki:pic_1";
public const string Pic2 = "urn:odnoklassniki:pic_2";
public const string Pic3 = "urn:odnoklassniki:pic_3";
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/aspnet-contrib/AspNet.Security.OAuth.Providers
* for more information concerning the license and the contributors participating to this project.
*/

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OAuth;

namespace AspNet.Security.OAuth.Odnoklassniki
{
/// <summary>
/// Default values used by the Odnoklassniki authentication middleware.
/// </summary>
public class OdnoklassnikiAuthenticationDefaults
{
/// <summary>
/// Default value for <see cref="AuthenticationScheme.Name"/>.
/// </summary>
public const string AuthenticationScheme = "Odnoklassniki";

/// <summary>
/// Default value for <see cref="AuthenticationScheme.DisplayName"/>.
/// </summary>
public const string DisplayName = "Odnoklassniki";

/// <summary>
/// Default value for <see cref="AuthenticationSchemeOptions.ClaimsIssuer"/>.
/// </summary>
public const string Issuer = "Odnoklassniki";

/// <summary>
/// Default value for <see cref="RemoteAuthenticationOptions.CallbackPath"/>.
/// </summary>
public const string CallbackPath = "/signin-ok";

/// <summary>
/// Default value for <see cref="OAuthOptions.AuthorizationEndpoint"/>.
/// </summary>
public const string AuthorizationEndpoint = "https://connect.ok.ru/oauth/authorize";

/// <summary>
/// Default value for <see cref="OAuthOptions.TokenEndpoint"/>.
/// </summary>
public const string TokenEndpoint = "https://api.ok.ru/oauth/token.do";

/// <summary>
/// Default value for <see cref="OAuthOptions.UserInformationEndpoint"/>.
/// </summary>
public const string UserInformationEndpoint = "https://api.ok.ru/fb.do";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/aspnet-contrib/AspNet.Security.OAuth.Providers
* for more information concerning the license and the contributors participating to this project.
*/

using System;
using AspNet.Security.OAuth.Odnoklassniki;
using JetBrains.Annotations;
using Microsoft.AspNetCore.Authentication;

namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Extension methods to add Odnoklassniki authentication capabilities to an HTTP application pipeline.
/// </summary>
public static class OdnoklassnikiAuthenticationExtensions
{
/// <summary>
/// Adds <see cref="OdnoklassnikiAuthenticationHandler"/> to the specified
/// <see cref="AuthenticationBuilder"/>, which enables Odnoklassniki authentication capabilities.
/// </summary>
/// <param name="builder">The authentication builder.</param>
/// <returns>The <see cref="AuthenticationBuilder"/>.</returns>
public static AuthenticationBuilder AddOdnoklassniki([NotNull] this AuthenticationBuilder builder)
{
return builder.AddOdnoklassniki(OdnoklassnikiAuthenticationDefaults.AuthenticationScheme, options => { });
}

/// <summary>
/// Adds <see cref="OdnoklassnikiAuthenticationHandler"/> to the specified
/// <see cref="AuthenticationBuilder"/>, which enables Odnoklassniki authentication capabilities.
/// </summary>
/// <param name="builder">The authentication builder.</param>
/// <param name="configuration">The delegate used to configure the Odnoklassniki options.</param>
public static AuthenticationBuilder AddOdnoklassniki(
[NotNull] this AuthenticationBuilder builder,
[NotNull] Action<OdnoklassnikiAuthenticationOptions> configuration)
{
return builder.AddOdnoklassniki(OdnoklassnikiAuthenticationDefaults.AuthenticationScheme, configuration);
}

/// <summary>
/// Adds <see cref="OdnoklassnikiAuthenticationHandler"/> to the specified
/// <see cref="AuthenticationBuilder"/>, which enables Odnoklassniki authentication capabilities.
/// </summary>
/// <param name="builder">The authentication builder.</param>
/// <param name="scheme">The authentication scheme associated with this instance.</param>
/// <param name="configuration">The delegate used to configure the Odnoklassniki options.</param>
/// <returns>The <see cref="AuthenticationBuilder"/>.</returns>
public static AuthenticationBuilder AddOdnoklassniki(
[NotNull] this AuthenticationBuilder builder, [NotNull] string scheme,
[NotNull] Action<OdnoklassnikiAuthenticationOptions> configuration)
{
return builder.AddOdnoklassniki(scheme, OdnoklassnikiAuthenticationDefaults.DisplayName, configuration);
}

/// <summary>
/// Adds <see cref="OdnoklassnikiAuthenticationHandler"/> to the specified
/// <see cref="AuthenticationBuilder"/>, which enables Odnoklassniki authentication capabilities.
/// </summary>
/// <param name="builder">The authentication builder.</param>
/// <param name="scheme">The authentication scheme associated with this instance.</param>
/// <param name="caption">The optional display name associated with this instance.</param>
/// <param name="configuration">The delegate used to configure the Odnoklassniki options.</param>
/// <returns>The <see cref="AuthenticationBuilder"/>.</returns>
public static AuthenticationBuilder AddOdnoklassniki(
[NotNull] this AuthenticationBuilder builder,
[NotNull] string scheme, [NotNull] string caption,
[NotNull] Action<OdnoklassnikiAuthenticationOptions> configuration)
{
return builder.AddOAuth<OdnoklassnikiAuthenticationOptions, OdnoklassnikiAuthenticationHandler>(scheme, caption, configuration);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/aspnet-contrib/AspNet.Security.OAuth.Providers
* for more information concerning the license and the contributors participating to this project.
*/

using System.Net.Http;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OAuth;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;

namespace AspNet.Security.OAuth.Odnoklassniki
{
public class OdnoklassnikiAuthenticationHandler : OAuthHandler<OdnoklassnikiAuthenticationOptions>
{
public OdnoklassnikiAuthenticationHandler(
[NotNull] IOptionsMonitor<OdnoklassnikiAuthenticationOptions> options,
[NotNull] ILoggerFactory logger,
[NotNull] UrlEncoder encoder,
[NotNull] ISystemClock clock)
: base(options, logger, encoder, clock)
{
}

protected override async Task<AuthenticationTicket> CreateTicketAsync([NotNull] ClaimsIdentity identity,
[NotNull] AuthenticationProperties properties, [NotNull] OAuthTokenResponse tokens)
{
var md5Inner = GetMd5(tokens.AccessToken + Options.ClientSecret);
var parametersForSig = PrepareParametersForSig(md5Inner);
var sig = GetMd5(parametersForSig);
var address = PrepareUserInfoAddress(tokens.AccessToken, sig);

var response = await Backchannel.GetAsync(address, Context.RequestAborted);
if (!response.IsSuccessStatusCode)
{
await LogErrorFromResponseAsync(response);

throw new HttpRequestException("An error occurred while retrieving the user profile.");
}

var payload = JObject.Parse(await response.Content.ReadAsStringAsync());

var principal = new ClaimsPrincipal(identity);

var context = new OAuthCreatingTicketContext(principal, properties, Context, Scheme, Options, Backchannel, tokens, payload);
context.RunClaimActions(payload);

await Options.Events.CreatingTicket(context);

return new AuthenticationTicket(context.Principal, context.Properties, Scheme.Name);
}

private static string GetMd5([NotNull] string value)
{
var md5 = MD5.Create();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MD5 implements IDisposable, so this needs to be in a using block.


var bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(value));
var stringBuilder = new StringBuilder();

foreach (var b in bytes)
{
stringBuilder.Append(b.ToString("x2"));
}

return stringBuilder.ToString();
}

private string PrepareParametersForSig([NotNull] string md5Inner)
{
return $"application_key={Options.ApplicationKey}" +
"format=json" +
"method=users.getCurrentUser" +
$"{md5Inner}";
}

private string PrepareUserInfoAddress([NotNull] string accessToken, [NotNull] string sig)
{
var address = QueryHelpers.AddQueryString(Options.UserInformationEndpoint, "application_key", Options.ApplicationKey);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could use a dictionary like many of the other providers do and do this as a single operation?

address = QueryHelpers.AddQueryString(address, "format", "json");
address = QueryHelpers.AddQueryString(address, "method", "users.getCurrentUser");
address = QueryHelpers.AddQueryString(address, "sig", sig);
address = QueryHelpers.AddQueryString(address, "access_token", accessToken);

return address;
}

private async Task LogErrorFromResponseAsync([NotNull] HttpResponseMessage response)
{
const string error = "An error occurred while retrieving the user profile: the remote server " +
"returned a {Status} response with the following payload: {Headers} {Body}.";

var body = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

Logger.LogError(error, response.StatusCode, response.Headers.ToString(), body);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/aspnet-contrib/AspNet.Security.OAuth.Providers
* for more information concerning the license and the contributors participating to this project.
*/

using System.Collections.Generic;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OAuth;
using Microsoft.AspNetCore.Http;
using static AspNet.Security.OAuth.Odnoklassniki.OdnoklassnikiAuthenticationConstants;

namespace AspNet.Security.OAuth.Odnoklassniki
{
/// <summary>
/// Defines a set of options used by <see cref="OdnoklassnikiAuthenticationHandler"/>.
/// </summary>
public class OdnoklassnikiAuthenticationOptions : OAuthOptions
{
public OdnoklassnikiAuthenticationOptions()
{
ClaimsIssuer = OdnoklassnikiAuthenticationDefaults.Issuer;

CallbackPath = new PathString(OdnoklassnikiAuthenticationDefaults.CallbackPath);

AuthorizationEndpoint = OdnoklassnikiAuthenticationDefaults.AuthorizationEndpoint;
TokenEndpoint = OdnoklassnikiAuthenticationDefaults.TokenEndpoint;
UserInformationEndpoint = OdnoklassnikiAuthenticationDefaults.UserInformationEndpoint;

Scope.Add("VALUABLE_ACCESS");
Scope.Add("LONG_ACCESS_TOKEN");
Scope.Add("GET_EMAIL");

ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "uid");
ClaimActions.MapJsonKey(ClaimTypes.Email, "email");
ClaimActions.MapJsonKey(ClaimTypes.GivenName, "first_name");
ClaimActions.MapJsonKey(ClaimTypes.Surname, "last_name");
ClaimActions.MapJsonKey(ClaimTypes.Gender, "gender");
ClaimActions.MapJsonKey(ClaimTypes.Locality, "locale");
ClaimActions.MapJsonKey(ClaimTypes.DateOfBirth, "birthday");
ClaimActions.MapJsonKey(Claims.Pic1, "pic_1");
ClaimActions.MapJsonKey(Claims.Pic2, "pic_2");
ClaimActions.MapJsonKey(Claims.Pic3, "pic_3");
}

/// <summary>
/// Gets the list of fields to retrieve from the user information endpoint.
/// See https://apiok.ru/dev/methods/rest/users/users.getCurrentUser for more information.
/// </summary>
public ISet<string> Fields { get; } = new HashSet<string>
{
"uid",
"email",
"first_name",
"last_name",
"gender",
"birthday",
"pic_1",
"pic_2",
"pic_3"
} as ISet<string>;

/// <summary>
/// Gets or sets the provider-assigned application key.
/// </summary>
public string ApplicationKey { get; set; }
}
}