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

Implement KOOK provider #754

Merged
merged 5 commits into from
Apr 16, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
8 changes: 8 additions & 0 deletions AspNet.Security.OAuth.Providers.sln
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "docs", "docs", "{C2CA4B38-A
docs\workweixin.md = docs\workweixin.md
docs\xumm.md = docs\xumm.md
docs\zendesk.md = docs\zendesk.md
docs\kook.md = docs\kook.md
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AspNet.Security.OAuth.Basecamp", "src\AspNet.Security.OAuth.Basecamp\AspNet.Security.OAuth.Basecamp.csproj", "{42306484-B2BF-4B52-B950-E0CDFA58B02A}"
Expand Down Expand Up @@ -295,6 +296,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AspNet.Security.OAuth.Smart
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
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AspNet.Security.OAuth.Kook", "src\AspNet.Security.OAuth.Kook\AspNet.Security.OAuth.Kook.csproj", "{101681FB-569F-4941-B943-2AD380039BE0}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -677,6 +680,10 @@ Global
{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
{101681FB-569F-4941-B943-2AD380039BE0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{101681FB-569F-4941-B943-2AD380039BE0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{101681FB-569F-4941-B943-2AD380039BE0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{101681FB-569F-4941-B943-2AD380039BE0}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -782,6 +789,7 @@ Global
{8E42EF81-A630-4BDB-B642-3F20C863F9BE} = {C1352FD3-AE8B-43EE-B45B-F6E0B3FBAC6D}
{68862DC5-65B7-4517-B909-AB334F9FCF6E} = {C1352FD3-AE8B-43EE-B45B-F6E0B3FBAC6D}
{E3CF7FFC-56A0-4033-87A9-BB3080CF030E} = {C1352FD3-AE8B-43EE-B45B-F6E0B3FBAC6D}
{101681FB-569F-4941-B943-2AD380039BE0} = {C1352FD3-AE8B-43EE-B45B-F6E0B3FBAC6D}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {C7B54DE2-6407-4802-AD9C-CE54BF414C8C}
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ We would love it if you could help contributing to this repository.
* [Ethan Celletti](https://github.com/Gekctek)
* [Floris Westerman](https://github.com/FWest98)
* [Galo](https://github.com/asiffermann)
* [Gehongyan](https://github.com/gehongyan)
* [Igor Simovic](https://github.com/igorsimovic)
* [James Holcomb](https://github.com/jamesholcomb)
* [Jason Loeffler](https://github.com/jmloeffler)
Expand Down Expand Up @@ -162,6 +163,7 @@ If a provider you're looking for does not exist, consider making a PR to add one
| KakaoTalk | [![NuGet](https://buildstats.info/nuget/AspNet.Security.OAuth.KakaoTalk?includePreReleases=false)](https://www.nuget.org/packages/AspNet.Security.OAuth.KakaoTalk/ "Download AspNet.Security.OAuth.KakaoTalk from NuGet.org") | [![MyGet](https://buildstats.info/myget/aspnet-contrib/AspNet.Security.OAuth.KakaoTalk?includePreReleases=true)](https://www.myget.org/feed/aspnet-contrib/package/nuget/AspNet.Security.OAuth.KakaoTalk "Download AspNet.Security.OAuth.KakaoTalk from MyGet.org") | [Documentation](https://developers.kakao.com/docs/latest/en/kakaologin/common "KakaoTalk developer documentation") |
| Keycloak | [![NuGet](https://buildstats.info/nuget/AspNet.Security.OAuth.Keycloak?includePreReleases=false)](https://www.nuget.org/packages/AspNet.Security.OAuth.Keycloak/ "Download AspNet.Security.OAuth.Keycloak from NuGet.org") | [![MyGet](https://buildstats.info/myget/aspnet-contrib/AspNet.Security.OAuth.Keycloak?includePreReleases=true)](https://www.myget.org/feed/aspnet-contrib/package/nuget/AspNet.Security.OAuth.Keycloak "Download AspNet.Security.OAuth.Keycloak from MyGet.org") | [Documentation](https://www.keycloak.org/docs/latest/authorization_services/#_service_overview "Keycloak developer documentation") |
| Kloudless | [![NuGet](https://buildstats.info/nuget/AspNet.Security.OAuth.Kloudless?includePreReleases=false)](https://www.nuget.org/packages/AspNet.Security.OAuth.Kloudless/ "Download AspNet.Security.OAuth.Kloudless from NuGet.org") | [![MyGet](https://buildstats.info/myget/aspnet-contrib/AspNet.Security.OAuth.Kloudless?includePreReleases=true)](https://www.myget.org/feed/aspnet-contrib/package/nuget/AspNet.Security.OAuth.Kloudless "Download AspNet.Security.OAuth.Kloudless from MyGet.org") | [Documentation](https://developers.kloudless.com/docs/v1/authentication "Kloudless developer documentation") |
| KOOK | [![NuGet](https://buildstats.info/nuget/AspNet.Security.OAuth.Kook?includePreReleases=false)](https://www.nuget.org/packages/AspNet.Security.OAuth.Kook/ "Download AspNet.Security.OAuth.Kook from NuGet.org") | [![MyGet](https://buildstats.info/myget/aspnet-contrib/AspNet.Security.OAuth.Kook?includePreReleases=true)](https://www.myget.org/feed/aspnet-contrib/package/nuget/AspNet.Security.OAuth.Kook "Download AspNet.Security.OAuth.Kook from MyGet.org") | [Documentation](https://developer.kookapp.cn/doc/oauth2 "KOOK developer documentation") |
| Kroger | [![NuGet](https://buildstats.info/nuget/AspNet.Security.OAuth.Kroger?includePreReleases=false)](https://www.nuget.org/packages/AspNet.Security.OAuth.Kroger/ "Download AspNet.Security.OAuth.Kroger from NuGet.org") | [![MyGet](https://buildstats.info/myget/aspnet-contrib/AspNet.Security.OAuth.Kroger?includePreReleases=true)](https://www.myget.org/feed/aspnet-contrib/package/nuget/AspNet.Security.OAuth.Kroger "Download AspNet.Security.OAuth.Kroger from MyGet.org") | [Documentation](https://developer.kroger.com/reference/#section/Authentication "Kroger developer documentation") |
| Lichess | [![NuGet](https://buildstats.info/nuget/AspNet.Security.OAuth.Lichess?includePreReleases=false)](https://www.nuget.org/packages/AspNet.Security.OAuth.Lichess/ "Download AspNet.Security.OAuth.Lichess from NuGet.org") | [![MyGet](https://buildstats.info/myget/aspnet-contrib/AspNet.Security.OAuth.Lichess?includePreReleases=true)](https://www.myget.org/feed/aspnet-contrib/package/nuget/AspNet.Security.OAuth.Lichess "Download AspNet.Security.OAuth.Lichess from MyGet.org") | [Documentation](https://lichess.org/api#section/Authentication "Lichess developer documentation") |
| Line | [![NuGet](https://buildstats.info/nuget/AspNet.Security.OAuth.Line?includePreReleases=false)](https://www.nuget.org/packages/AspNet.Security.OAuth.Line/ "Download AspNet.Security.OAuth.Line from NuGet.org") | [![MyGet](https://buildstats.info/myget/aspnet-contrib/AspNet.Security.OAuth.Line?includePreReleases=true)](https://www.myget.org/feed/aspnet-contrib/package/nuget/AspNet.Security.OAuth.Line "Download AspNet.Security.OAuth.Line from MyGet.org") | [Documentation](https://developers.line.biz/en/docs/line-login/integrate-line-login "Line developer documentation") |
Expand Down
1 change: 1 addition & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ covered by the section above.
| Huawei | _Optional_ | [Documentation](huawei.md "Huawei provider documentation") |
| Instagram | _Optional_ | [Documentation](instagram.md "Instagram provider documentation") |
| Kloudless | _Optional_ | [Documentation](kloudless.md "Kloudless provider documentation") |
| KOOK | _Optional_ | [Documentation](kook.md "KOOK provider documentation") |
| Line | _Optional_ | [Documentation](line.md "Line provider documentation") |
| LinkedIn | _Optional_ | [Documentation](linkedin.md "LinkedIn provider documentation") |
| Odnoklassniki | _Optional_ | [Documentation](odnoklassniki.md "Odnoklassniki provider documentation") |
Expand Down
25 changes: 25 additions & 0 deletions docs/kook.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Integrating the KOOK Provider

## Example

```csharp
services.AddAuthentication(options => /* Auth configuration */)
.AddKook(options =>
{
options.ClientId = "my-client-id";
options.ClientSecret = "my-client-secret";

// The scope get_user_info is added by default
// Please make sure the scope get_user_info is enabled in your KOOK developer center
// Hence, whether to add the scope get_user_info here manually is optional
// options.Scope.Add("get_user_info");
martincostello marked this conversation as resolved.
Show resolved Hide resolved
});
```

## Required Additional Settings

_None._

## Optional Settings

_None._
23 changes: 23 additions & 0 deletions src/AspNet.Security.OAuth.Kook/AspNet.Security.OAuth.Kook.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>$(DefaultNetCoreTargetFramework)</TargetFrameworks>
</PropertyGroup>

<!-- TODO Remove once published to NuGet.org -->
<PropertyGroup>
<DisablePackageBaselineValidation>true</DisablePackageBaselineValidation>
</PropertyGroup>
martincostello marked this conversation as resolved.
Show resolved Hide resolved

<PropertyGroup>
<Description>ASP.NET Core security middleware enabling Kook authentication.</Description>
martincostello marked this conversation as resolved.
Show resolved Hide resolved
<Authors>Gehongyan</Authors>
<PackageTags>aspnetcore;authentication;kaiheila;kook;kookapp;oauth;security</PackageTags>
</PropertyGroup>

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

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

/// <summary>
/// Contains constants specific to the <see cref="KookAuthenticationHandler"/>.
/// </summary>
public static class KookAuthenticationConstants
{
public static class Claims
{
public const string IsOnline = "urn:kook:user:is_online";
public const string IsBanned = "urn:kook:user:is_banned";
public const string OperatingSystem = "urn:kook:user:operating_system";
public const string AvatarUrl = "urn:kook:user:avatar:url";
public const string BannerUrl = "urn:kook:user:banner:url";
public const string IsBot = "urn:kook:user:is_bot";
public const string IsMobileVerified = "urn:kook:user:is_mobile_verified";
public const string IdentifyNumber = "urn:kook:user:identify_num";
}
}
48 changes: 48 additions & 0 deletions src/AspNet.Security.OAuth.Kook/KookAuthenticationDefaults.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.Kook;

/// <summary>
/// Default values used by the Kook authentication middleware.
/// </summary>
public static class KookAuthenticationDefaults
{
/// <summary>
/// Default value for <see cref="Microsoft.AspNetCore.Authentication.AuthenticationScheme.Name"/>.
/// </summary>
public const string AuthenticationScheme = "Kook";

/// <summary>
/// Default value for <see cref="Microsoft.AspNetCore.Authentication.AuthenticationScheme.DisplayName"/>.
/// </summary>
public static readonly string DisplayName = "Kook";

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

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

/// <summary>
/// Default value for <see cref="OAuthOptions.AuthorizationEndpoint"/>.
/// </summary>
public static readonly string AuthorizationEndpoint = "https://www.kookapp.cn/app/oauth2/authorize";

/// <summary>
/// Default value for <see cref="OAuthOptions.TokenEndpoint"/>.
/// </summary>
public static readonly string TokenEndpoint = "https://www.kookapp.cn/api/oauth2/token";

/// <summary>
/// Default value for <see cref="OAuthOptions.UserInformationEndpoint"/>.
/// </summary>
public static readonly string UserInformationEndpoint = "https://www.kookapp.cn/api/v3/user/me";
}
74 changes: 74 additions & 0 deletions src/AspNet.Security.OAuth.Kook/KookAuthenticationExtensions.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.Kook;

namespace Microsoft.Extensions.DependencyInjection;

/// <summary>
/// Extension methods to add Kook authentication capabilities to an HTTP application pipeline.
/// </summary>
public static class KookAuthenticationExtensions
{
/// <summary>
/// Adds <see cref="KookAuthenticationHandler"/> to the specified
/// <see cref="AuthenticationBuilder"/>, which enables Kook authentication capabilities.
/// </summary>
/// <param name="builder">The authentication builder.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
public static AuthenticationBuilder AddKook([NotNull] this AuthenticationBuilder builder)
{
return builder.AddKook(KookAuthenticationDefaults.AuthenticationScheme, options => { });
}

/// <summary>
/// Adds <see cref="KookAuthenticationHandler"/> to the specified
/// <see cref="AuthenticationBuilder"/>, which enables Kook 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>A reference to this instance after the operation has completed.</returns>
public static AuthenticationBuilder AddKook(
[NotNull] this AuthenticationBuilder builder,
[NotNull] Action<KookAuthenticationOptions> configuration)
{
return builder.AddKook(KookAuthenticationDefaults.AuthenticationScheme, configuration);
}

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

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

namespace AspNet.Security.OAuth.Kook;

public partial class KookAuthenticationHandler : OAuthHandler<KookAuthenticationOptions>
{
public KookAuthenticationHandler(
[NotNull] IOptionsMonitor<KookAuthenticationOptions> 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)
{
using var request = new HttpRequestMessage(HttpMethod.Get, Options.UserInformationEndpoint);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokens.AccessToken);

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 code = payload.RootElement.GetProperty("code").GetInt32();

if (code != 0)
{
Log.UserProfileErrorCode(Logger, code, payload.RootElement.GetString("message"));
throw new HttpRequestException("An error occurred while retrieving the user profile.");
}

var principal = new ClaimsPrincipal(identity);
var user = payload.RootElement.GetProperty("data");

identity.AddClaim(new Claim(KookAuthenticationConstants.Claims.IsBanned, (user.GetProperty("status").GetInt32() == 10).ToString()));
martincostello marked this conversation as resolved.
Show resolved Hide resolved

var context = new OAuthCreatingTicketContext(principal, properties, Context, Scheme, Options, Backchannel, tokens, user);
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);

[LoggerMessage(2, LogLevel.Error, "An error occurred while retrieving the user profile: the remote server returned a {Status} response with the following message: {ErrorMessage}.")]
internal static partial void UserProfileErrorCode(
ILogger logger,
int status,
string? errorMessage);
}
}
Loading