Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Huawei provider. #742

Merged
merged 5 commits into from
Nov 1, 2022
Merged
Show file tree
Hide file tree
Changes from 3 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
7 changes: 7 additions & 0 deletions AspNet.Security.OAuth.Providers.sln
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AspNet.Security.OAuth.Kroge
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AspNet.Security.OAuth.Xumm", "src\AspNet.Security.OAuth.Xumm\AspNet.Security.OAuth.Xumm.csproj", "{8E42EF81-A630-4BDB-B642-3F20C863F9BE}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AspNet.Security.OAuth.Huawei", "src\AspNet.Security.OAuth.Huawei\AspNet.Security.OAuth.Huawei.csproj", "{E3CF7FFC-56A0-4033-87A9-BB3080CF030E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -664,6 +666,10 @@ Global
{8E42EF81-A630-4BDB-B642-3F20C863F9BE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8E42EF81-A630-4BDB-B642-3F20C863F9BE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8E42EF81-A630-4BDB-B642-3F20C863F9BE}.Release|Any CPU.Build.0 = Release|Any CPU
{E3CF7FFC-56A0-4033-87A9-BB3080CF030E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E3CF7FFC-56A0-4033-87A9-BB3080CF030E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E3CF7FFC-56A0-4033-87A9-BB3080CF030E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E3CF7FFC-56A0-4033-87A9-BB3080CF030E}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -767,6 +773,7 @@ Global
{B8F9B052-84BF-436C-B22B-CEBD5EB1F8E3} = {C1352FD3-AE8B-43EE-B45B-F6E0B3FBAC6D}
{8C7A98A6-5F61-492B-980D-0A9F5F9F5C73} = {C1352FD3-AE8B-43EE-B45B-F6E0B3FBAC6D}
{8E42EF81-A630-4BDB-B642-3F20C863F9BE} = {C1352FD3-AE8B-43EE-B45B-F6E0B3FBAC6D}
{E3CF7FFC-56A0-4033-87A9-BB3080CF030E} = {C1352FD3-AE8B-43EE-B45B-F6E0B3FBAC6D}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {C7B54DE2-6407-4802-AD9C-CE54BF414C8C}
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ If a provider you're looking for does not exist, consider making a PR to add one
| Gitter | [![NuGet](https://buildstats.info/nuget/AspNet.Security.OAuth.Gitter?includePreReleases=false)](https://www.nuget.org/packages/AspNet.Security.OAuth.Gitter/ "Download AspNet.Security.OAuth.Gitter from NuGet.org") | [![MyGet](https://buildstats.info/myget/aspnet-contrib/AspNet.Security.OAuth.Gitter?includePreReleases=true)](https://www.myget.org/feed/aspnet-contrib/package/nuget/AspNet.Security.OAuth.Gitter "Download AspNet.Security.OAuth.Gitter from MyGet.org") | [Documentation](https://developer.gitter.im/docs/authentication "Gitter developer documentation") |
| Harvest | [![NuGet](https://buildstats.info/nuget/AspNet.Security.OAuth.Harvest?includePreReleases=false)](https://www.nuget.org/packages/AspNet.Security.OAuth.Harvest/ "Download AspNet.Security.OAuth.Harvest from NuGet.org") | [![MyGet](https://buildstats.info/myget/aspnet-contrib/AspNet.Security.OAuth.Harvest?includePreReleases=true)](https://www.myget.org/feed/aspnet-contrib/package/nuget/AspNet.Security.OAuth.Harvest "Download AspNet.Security.OAuth.Harvest from MyGet.org") | [Documentation](https://help.getharvest.com/api-v1/authentication/authentication/oauth/ "Harvest developer documentation") |
| HealthGraph (Runkeeper) | [![NuGet](https://buildstats.info/nuget/AspNet.Security.OAuth.HealthGraph?includePreReleases=false)](https://www.nuget.org/packages/AspNet.Security.OAuth.HealthGraph/ "Download AspNet.Security.OAuth.HealthGraph from NuGet.org") | [![MyGet](https://buildstats.info/myget/aspnet-contrib/AspNet.Security.OAuth.HealthGraph?includePreReleases=true)](https://www.myget.org/feed/aspnet-contrib/package/nuget/AspNet.Security.OAuth.HealthGraph "Download AspNet.Security.OAuth.HealthGraph from MyGet.org") | N/A |
| Huawei | [![NuGet](https://buildstats.info/nuget/AspNet.Security.OAuth.Huawei?includePreReleases=false)](https://www.nuget.org/packages/AspNet.Security.OAuth.Huawei/ "Download AspNet.Security.OAuth.Huawei from NuGet.org") | [![MyGet](https://buildstats.info/myget/aspnet-contrib/AspNet.Security.OAuth.Huawei?includePreReleases=true)](https://www.myget.org/feed/aspnet-contrib/package/nuget/AspNet.Security.OAuth.Huawei "Download AspNet.Security.OAuth.Huawei from MyGet.org") | [Documentation](https://developer.huawei.com/consumer/en/hms/huawei-accountkit "Huawei developer documentation") |
| HubSpot | [![NuGet](https://buildstats.info/nuget/AspNet.Security.OAuth.HubSpot?includePreReleases=false)](https://www.nuget.org/packages/AspNet.Security.OAuth.HubSpot/ "Download AspNet.Security.OAuth.HubSpot from NuGet.org") | [![MyGet](https://buildstats.info/myget/aspnet-contrib/AspNet.Security.OAuth.HubSpot?includePreReleases=true)](https://www.myget.org/feed/aspnet-contrib/package/nuget/AspNet.Security.OAuth.HubSpot "Download AspNet.Security.OAuth.HubSpot from MyGet.org") | [Documentation](https://developers.hubspot.com/docs "HubSpot developer documentation") |
| Imgur | [![NuGet](https://buildstats.info/nuget/AspNet.Security.OAuth.Imgur?includePreReleases=false)](https://www.nuget.org/packages/AspNet.Security.OAuth.Imgur/ "Download AspNet.Security.OAuth.Imgur from NuGet.org") | [![MyGet](https://buildstats.info/myget/aspnet-contrib/AspNet.Security.OAuth.Imgur?includePreReleases=true)](https://www.myget.org/feed/aspnet-contrib/package/nuget/AspNet.Security.OAuth.Imgur "Download AspNet.Security.OAuth.Imgur from MyGet.org") | [Documentation](https://apidocs.imgur.com/?version=latest#authorization-and-oauth "Imgur developer documentation") |
| Instagram | [![NuGet](https://buildstats.info/nuget/AspNet.Security.OAuth.Instagram?includePreReleases=false)](https://www.nuget.org/packages/AspNet.Security.OAuth.Instagram/ "Download AspNet.Security.OAuth.Instagram from NuGet.org") | [![MyGet](https://buildstats.info/myget/aspnet-contrib/AspNet.Security.OAuth.Instagram?includePreReleases=true)](https://www.myget.org/feed/aspnet-contrib/package/nuget/AspNet.Security.OAuth.Instagram "Download AspNet.Security.OAuth.Instagram from MyGet.org") | [Documentation](https://www.instagram.com/developer/authentication/ "Instagram developer documentation") |
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<DisablePackageBaselineValidation>true</DisablePackageBaselineValidation>
<PackageValidationBaselineVersion>6.0.13</PackageValidationBaselineVersion>
<TargetFrameworks>$(DefaultNetCoreTargetFramework)</TargetFrameworks>
</PropertyGroup>

<PropertyGroup>
<Description>ASP.NET Core security middleware enabling Huawei authentication.</Description>
<Authors>Vicente Yu</Authors>
<PackageTags>aspnetcore;authentication;huawei;oauth;security</PackageTags>
</PropertyGroup>

<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="JetBrains.Annotations" PrivateAssets="All" />
</ItemGroup>

</Project>
18 changes: 18 additions & 0 deletions src/AspNet.Security.OAuth.Huawei/HuaweiAuthenticationConstants.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/*
* 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.Huawei;

/// <summary>
/// Contains constants specific to the <see cref="HuaweiAuthenticationHandler"/>.
/// </summary>
public static class HuaweiAuthenticationConstants
{
public static class Claims
{
public const string Avatar = "urn:huawei:avatar";
}
}
48 changes: 48 additions & 0 deletions src/AspNet.Security.OAuth.Huawei/HuaweiAuthenticationDefaults.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
* 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.Huawei;

/// <summary>
/// Default values for Huawei authentication.
/// </summary>
public static class HuaweiAuthenticationDefaults
{
/// <summary>
/// Default value for <see cref="AuthenticationScheme.Name"/>.
/// </summary>
public const string AuthenticationScheme = "Huawei";

/// <summary>
/// Default value for <see cref="AuthenticationScheme.DisplayName"/>.
/// </summary>
public static readonly string DisplayName = "Huawei";

/// <summary>
/// Default value for <see cref="RemoteAuthenticationOptions.CallbackPath"/>.
/// </summary>
public static readonly string CallbackPath = "/signin-huawei";

/// <summary>
/// Default value for <see cref="AuthenticationSchemeOptions.ClaimsIssuer"/>.
/// </summary>
public static readonly string Issuer = "Huawei";

/// <summary>
/// Default value for <see cref="OAuthOptions.AuthorizationEndpoint"/>.
/// </summary>
public static readonly string AuthorizationEndpoint = "https://oauth-login.cloud.huawei.com/oauth2/v3/authorize";

/// <summary>
/// Default value for <see cref="OAuthOptions.TokenEndpoint"/>.
/// </summary>
public static readonly string TokenEndpoint = "https://oauth-login.cloud.huawei.com/oauth2/v3/token";

/// <summary>
/// Default value for <see cref="OAuthOptions.UserInformationEndpoint"/>.
/// </summary>
public static readonly string UserInformationEndpoint = "https://account.cloud.huawei.com/rest.php";
}
74 changes: 74 additions & 0 deletions src/AspNet.Security.OAuth.Huawei/HuaweiAuthenticationExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
* 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 AspNet.Security.OAuth.Huawei;

namespace Microsoft.Extensions.DependencyInjection;

/// <summary>
/// Extension methods to add Huawei authentication capabilities to an HTTP application pipeline.
/// </summary>
public static class HuaweiAuthenticationExtensions
{
/// <summary>
/// Adds <see cref="HuaweiAuthenticationHandler"/> to the specified
/// <see cref="AuthenticationBuilder"/>, which enables Huawei authentication capabilities.
/// </summary>
/// <param name="builder">The authentication builder.</param>
/// <returns>The <see cref="AuthenticationBuilder"/>.</returns>
public static AuthenticationBuilder AddHuawei([NotNull] this AuthenticationBuilder builder)
{
return builder.AddHuawei(HuaweiAuthenticationDefaults.AuthenticationScheme, _ => { });
}

/// <summary>
/// Adds <see cref="HuaweiAuthenticationHandler"/> to the specified
/// <see cref="AuthenticationBuilder"/>, which enables Huawei authentication capabilities.
/// </summary>
/// <param name="builder">The authentication builder.</param>
/// <param name="configuration">The delegate used to configure the OpenID 2.0 options.</param>
/// <returns>The <see cref="AuthenticationBuilder"/>.</returns>
public static AuthenticationBuilder AddHuawei(
[NotNull] this AuthenticationBuilder builder,
[NotNull] Action<HuaweiAuthenticationOptions> configuration)
{
return builder.AddHuawei(HuaweiAuthenticationDefaults.AuthenticationScheme, configuration);
}

/// <summary>
/// Adds <see cref="HuaweiAuthenticationHandler"/> to the specified
/// <see cref="AuthenticationBuilder"/>, which enables Huawei 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 Huawei options.</param>
/// <returns>The <see cref="AuthenticationBuilder"/>.</returns>
public static AuthenticationBuilder AddHuawei(
[NotNull] this AuthenticationBuilder builder,
[NotNull] string scheme,
[NotNull] Action<HuaweiAuthenticationOptions> configuration)
{
return builder.AddHuawei(scheme, HuaweiAuthenticationDefaults.DisplayName, configuration);
}

/// <summary>
/// Adds <see cref="HuaweiAuthenticationHandler"/> to the specified
/// <see cref="AuthenticationBuilder"/>, which enables Huawei 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 Huawei options.</param>
/// <returns>The <see cref="AuthenticationBuilder"/>.</returns>
public static AuthenticationBuilder AddHuawei(
[NotNull] this AuthenticationBuilder builder,
[NotNull] string scheme,
[CanBeNull] string caption,
[NotNull] Action<HuaweiAuthenticationOptions> configuration)
{
return builder.AddOAuth<HuaweiAuthenticationOptions, HuaweiAuthenticationHandler>(scheme, caption, configuration);
}
}
78 changes: 78 additions & 0 deletions src/AspNet.Security.OAuth.Huawei/HuaweiAuthenticationHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
* 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.Security.Claims;
using System.Text.Encodings.Web;
using System.Text.Json;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace AspNet.Security.OAuth.Huawei;

public partial class HuaweiAuthenticationHandler : OAuthHandler<HuaweiAuthenticationOptions>
{
public HuaweiAuthenticationHandler(
[NotNull] IOptionsMonitor<HuaweiAuthenticationOptions> 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 address = QueryHelpers.AddQueryString(Options.UserInformationEndpoint, "nsp_svc", "GOpen.User.getInfo");

var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("getNickName", Options.GetNickName ? "1" : "0"),
new KeyValuePair<string, string>("access_token", tokens.AccessToken!)
});

using var request = new HttpRequestMessage(HttpMethod.Post, address);
request.Content = content;

using var response = await Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, Context.RequestAborted);
if (!response.IsSuccessStatusCode)
{
await Log.UserProfileErrorAsync(Logger, response, Context.RequestAborted);
throw new HttpRequestException("An error occurred while retrieving the user profile.");
}

using var payload = JsonDocument.Parse(await response.Content.ReadAsStringAsync(Context.RequestAborted));

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

await Events.CreatingTicket(context);
return new AuthenticationTicket(context.Principal!, context.Properties, Scheme.Name);
}

private static partial class Log
{
internal static async Task UserProfileErrorAsync(ILogger logger, HttpResponseMessage response, CancellationToken cancellationToken)
{
UserProfileError(
logger,
response.StatusCode,
response.Headers.ToString(),
await response.Content.ReadAsStringAsync(cancellationToken));
}

[LoggerMessage(1, LogLevel.Error, "An error occurred while retrieving the user profile: the remote server returned a {Status} response with the following payload: {Headers} {Body}.")]
private static partial void UserProfileError(
ILogger logger,
System.Net.HttpStatusCode status,
string headers,
string body);
}
}
35 changes: 35 additions & 0 deletions src/AspNet.Security.OAuth.Huawei/HuaweiAuthenticationOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* 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.Security.Claims;
using static AspNet.Security.OAuth.Huawei.HuaweiAuthenticationConstants;

namespace AspNet.Security.OAuth.Huawei;

/// <summary>
/// Defines a set of options used by <see cref="HuaweiAuthenticationHandler"/>.
/// </summary>
public class HuaweiAuthenticationOptions : OAuthOptions
{
public HuaweiAuthenticationOptions()
{
ClaimsIssuer = HuaweiAuthenticationDefaults.Issuer;
CallbackPath = HuaweiAuthenticationDefaults.CallbackPath;

AuthorizationEndpoint = HuaweiAuthenticationDefaults.AuthorizationEndpoint;
TokenEndpoint = HuaweiAuthenticationDefaults.TokenEndpoint;
UserInformationEndpoint = HuaweiAuthenticationDefaults.UserInformationEndpoint;

ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "openID");
ClaimActions.MapJsonKey(ClaimTypes.Name, "displayName");
ClaimActions.MapJsonKey(ClaimTypes.Email, "email");
ClaimActions.MapJsonKey(Claims.Avatar, "headPictureURL");

Scope.Add("openid");
}

public bool GetNickName { get; set; }
vicenteyu marked this conversation as resolved.
Show resolved Hide resolved
}
47 changes: 47 additions & 0 deletions test/AspNet.Security.OAuth.Providers.Tests/Huawei/HuaweiTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* 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.Huawei;

public class HuaweiTests : OAuthTests<HuaweiAuthenticationOptions>
{
public HuaweiTests(ITestOutputHelper outputHelper)
{
OutputHelper = outputHelper;
}

public override string DefaultScheme => HuaweiAuthenticationDefaults.AuthenticationScheme;

protected internal override void RegisterAuthentication(AuthenticationBuilder builder)
{
builder.AddHuawei(options =>
{
options.GetNickName = true;

options.Scope.Add("profile");
options.Scope.Add("email");

ConfigureDefaults(builder, options);
});
}

[Theory]
vicenteyu marked this conversation as resolved.
Show resolved Hide resolved
[InlineData(ClaimTypes.NameIdentifier, "test-name-identifier")]
[InlineData(ClaimTypes.Name, "test-display-name")]
[InlineData(HuaweiAuthenticationConstants.Claims.Avatar, "test-head-picture-url.jpg")]
[InlineData(ClaimTypes.Email, "test-email@test")]
martincostello marked this conversation as resolved.
Show resolved Hide resolved
public async Task Can_Sign_In_Using_Huawei(string claimType, string claimValue)
{
// Arrange
using var server = CreateTestServer();

// Act
var claims = await AuthenticateUserAsync(server);

// Assert
AssertClaim(claims, claimType, claimValue);
}
}
Loading