Skip to content

Commit

Permalink
Add Feishu provider (#709)
Browse files Browse the repository at this point in the history
* Add Feishu provider

Signed-off-by: Vicente Yu <yxr@live.cn>

* Add Feishu provider.

Signed-off-by: Vicente Yu <yxr@live.cn>
  • Loading branch information
vicenteyu committed Aug 24, 2022
1 parent 34e7b72 commit f1e2f76
Show file tree
Hide file tree
Showing 10 changed files with 353 additions and 0 deletions.
7 changes: 7 additions & 0 deletions AspNet.Security.OAuth.Providers.sln
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AspNet.Security.OAuth.HubSp
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AspNet.Security.OAuth.Snapchat", "src\AspNet.Security.OAuth.Snapchat\AspNet.Security.OAuth.Snapchat.csproj", "{ECD22287-9B9F-489A-84A7-E66D65A39D73}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AspNet.Security.OAuth.Feishu", "src\AspNet.Security.OAuth.Feishu\AspNet.Security.OAuth.Feishu.csproj", "{B8F9B052-84BF-436C-B22B-CEBD5EB1F8E3}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -645,6 +647,10 @@ Global
{ECD22287-9B9F-489A-84A7-E66D65A39D73}.Debug|Any CPU.Build.0 = Debug|Any CPU
{ECD22287-9B9F-489A-84A7-E66D65A39D73}.Release|Any CPU.ActiveCfg = Release|Any CPU
{ECD22287-9B9F-489A-84A7-E66D65A39D73}.Release|Any CPU.Build.0 = Release|Any CPU
{B8F9B052-84BF-436C-B22B-CEBD5EB1F8E3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B8F9B052-84BF-436C-B22B-CEBD5EB1F8E3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B8F9B052-84BF-436C-B22B-CEBD5EB1F8E3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B8F9B052-84BF-436C-B22B-CEBD5EB1F8E3}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -745,6 +751,7 @@ Global
{289A91E9-81A9-422D-9CCD-12819081A29A} = {C1352FD3-AE8B-43EE-B45B-F6E0B3FBAC6D}
{23E576EB-6514-4617-8F04-FE7D5540136D} = {C1352FD3-AE8B-43EE-B45B-F6E0B3FBAC6D}
{ECD22287-9B9F-489A-84A7-E66D65A39D73} = {C1352FD3-AE8B-43EE-B45B-F6E0B3FBAC6D}
{B8F9B052-84BF-436C-B22B-CEBD5EB1F8E3} = {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 @@ -93,6 +93,7 @@ We would love it if you could help contributing to this repository.
* [Yannic Smeets](https://github.com/yannicsmeets)
* [zAfLu](https://github.com/zAfLu)
* [zhengchun](https://github.com/zhengchun)
* [Vicente Yu](https://github.com/vicenteyu)
* [Volodymyr Baydalka](https://github.com/zVolodymyr)
* [Logan Dam](https://github.com/biltongza)

Expand Down Expand Up @@ -141,6 +142,7 @@ If a provider you're looking for does not exist, consider making a PR to add one
| eBay | [![NuGet](https://buildstats.info/nuget/AspNet.Security.OAuth.Ebay?includePreReleases=false)](https://www.nuget.org/packages/AspNet.Security.OAuth.Ebay/ "Download AspNet.Security.OAuth.Ebay from NuGet.org") | [![MyGet](https://buildstats.info/myget/aspnet-contrib/AspNet.Security.OAuth.Ebay?includePreReleases=true)](https://www.myget.org/feed/aspnet-contrib/package/nuget/AspNet.Security.OAuth.Ebay "Download AspNet.Security.OAuth.Ebay from MyGet.org") | [Documentation](https://developer.ebay.com/api-docs/static/oauth-tokens.html "eBay developer documentation") |
| EVEOnline | [![NuGet](https://buildstats.info/nuget/AspNet.Security.OAuth.EVEOnline?includePreReleases=false)](https://www.nuget.org/packages/AspNet.Security.OAuth.EVEOnline/ "Download AspNet.Security.OAuth.EVEOnline from NuGet.org") | [![MyGet](https://buildstats.info/myget/aspnet-contrib/AspNet.Security.OAuth.EVEOnline?includePreReleases=true)](https://www.myget.org/feed/aspnet-contrib/package/nuget/AspNet.Security.OAuth.EVEOnline "Download AspNet.Security.OAuth.EVEOnline from MyGet.org") | [Documentation](https://github.com/esi/esi-docs/blob/master/docs/sso/web_based_sso_flow.md "EVEOnline developer documentation") |
| ExactOnline | [![NuGet](https://buildstats.info/nuget/AspNet.Security.OAuth.ExactOnline?includePreReleases=false)](https://www.nuget.org/packages/AspNet.Security.OAuth.ExactOnline/ "Download AspNet.Security.OAuth.ExactOnline from NuGet.org") | [![MyGet](https://buildstats.info/myget/aspnet-contrib/AspNet.Security.OAuth.ExactOnline?includePreReleases=true)](https://www.myget.org/feed/aspnet-contrib/package/nuget/AspNet.Security.OAuth.ExactOnline "Download AspNet.Security.OAuth.ExactOnline from MyGet.org") | [Documentation](https://support.exactonline.com/community/s/knowledge-base#All-All-DNO-Content-gettingstarted "ExactOnline developer documentation") |
| Feishu | [![NuGet](https://buildstats.info/nuget/AspNet.Security.OAuth.Feishu?includePreReleases=false)](https://www.nuget.org/packages/AspNet.Security.OAuth.Feishu/ "Download AspNet.Security.OAuth.Feishu from NuGet.org") | [![MyGet](https://buildstats.info/myget/aspnet-contrib/AspNet.Security.OAuth.Feishu?includePreReleases=true)](https://www.myget.org/feed/aspnet-contrib/package/nuget/AspNet.Security.OAuth.Feishu "Download AspNet.Security.OAuth.Feishu from MyGet.org") | [Documentation](https://open.feishu.cn/document/common-capabilities/sso/web-application-sso/web-app-overview "Feishu developer documentation") |
| Fitbit | [![NuGet](https://buildstats.info/nuget/AspNet.Security.OAuth.Fitbit?includePreReleases=false)](https://www.nuget.org/packages/AspNet.Security.OAuth.Fitbit/ "Download AspNet.Security.OAuth.Fitbit from NuGet.org") | [![MyGet](https://buildstats.info/myget/aspnet-contrib/AspNet.Security.OAuth.Fitbit?includePreReleases=true)](https://www.myget.org/feed/aspnet-contrib/package/nuget/AspNet.Security.OAuth.Fitbit "Download AspNet.Security.OAuth.Fitbit from MyGet.org") | [Documentation](https://dev.fitbit.com/build/reference/web-api/oauth2/ "Fitbit developer documentation") |
| Foursquare | [![NuGet](https://buildstats.info/nuget/AspNet.Security.OAuth.Foursquare?includePreReleases=false)](https://www.nuget.org/packages/AspNet.Security.OAuth.Foursquare/ "Download AspNet.Security.OAuth.Foursquare from NuGet.org") | [![MyGet](https://buildstats.info/myget/aspnet-contrib/AspNet.Security.OAuth.Foursquare?includePreReleases=true)](https://www.myget.org/feed/aspnet-contrib/package/nuget/AspNet.Security.OAuth.Foursquare "Download AspNet.Security.OAuth.Foursquare from MyGet.org") | [Documentation](https://developer.foursquare.com/docs/api/configuration/authentication "Foursquare developer documentation") |
| Gitee | [![NuGet](https://buildstats.info/nuget/AspNet.Security.OAuth.Gitee?includePreReleases=false)](https://www.nuget.org/packages/AspNet.Security.OAuth.Gitee/ "Download AspNet.Security.OAuth.Gitee from NuGet.org") | [![MyGet](https://buildstats.info/myget/aspnet-contrib/AspNet.Security.OAuth.Gitee?includePreReleases=true)](https://www.myget.org/feed/aspnet-contrib/package/nuget/AspNet.Security.OAuth.Gitee "Download AspNet.Security.OAuth.Gitee from MyGet.org") | [Documentation](https://gitee.com/api/v5/oauth_doc#/ "Gitee 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.9</PackageValidationBaselineVersion>
<TargetFrameworks>$(DefaultNetCoreTargetFramework)</TargetFrameworks>
</PropertyGroup>

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

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

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

/// <summary>
/// Contains constants specific to the <see cref="FeishuAuthenticationHandler"/>.
/// </summary>
public static class FeishuAuthenticationConstants
{
public static class Claims
{
public const string UnionId = "urn:feishu:unionid";
public const string Avatar = "urn:feishu:avatar";
}
}
48 changes: 48 additions & 0 deletions src/AspNet.Security.OAuth.Feishu/FeishuAuthenticationDefaults.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.Feishu;

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

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

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

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

/// <summary>
/// Default value for <see cref="OAuthOptions.AuthorizationEndpoint"/>.
/// </summary>
public static readonly string AuthorizationEndpoint = "https://passport.feishu.cn/suite/passport/oauth/authorize";

/// <summary>
/// Default value for <see cref="OAuthOptions.TokenEndpoint"/>.
/// </summary>
public static readonly string TokenEndpoint = "https://passport.feishu.cn/suite/passport/oauth/token";

/// <summary>
/// Default value for <see cref="OAuthOptions.UserInformationEndpoint"/>.
/// </summary>
public static readonly string UserInformationEndpoint = "https://passport.feishu.cn/suite/passport/oauth/userinfo";
}
74 changes: 74 additions & 0 deletions src/AspNet.Security.OAuth.Feishu/FeishuAuthenticationExtensions.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.Feishu;

namespace Microsoft.Extensions.DependencyInjection;

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

/// <summary>
/// Adds <see cref="FeishuAuthenticationHandler"/> to the specified
/// <see cref="AuthenticationBuilder"/>, which enables Feishu 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 AddFeishu(
[NotNull] this AuthenticationBuilder builder,
[NotNull] Action<FeishuAuthenticationOptions> configuration)
{
return builder.AddFeishu(FeishuAuthenticationDefaults.AuthenticationScheme, configuration);
}

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

/// <summary>
/// Adds <see cref="FeishuAuthenticationHandler"/> to the specified
/// <see cref="AuthenticationBuilder"/>, which enables Feishu 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 Feishu options.</param>
/// <returns>The <see cref="AuthenticationBuilder"/>.</returns>
public static AuthenticationBuilder AddFeishu(
[NotNull] this AuthenticationBuilder builder,
[NotNull] string scheme,
[CanBeNull] string caption,
[NotNull] Action<FeishuAuthenticationOptions> configuration)
{
return builder.AddOAuth<FeishuAuthenticationOptions, FeishuAuthenticationHandler>(scheme, caption, configuration);
}
}
71 changes: 71 additions & 0 deletions src/AspNet.Security.OAuth.Feishu/FeishuAuthenticationHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*
* 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.Feishu;

public partial class FeishuAuthenticationHandler : OAuthHandler<FeishuAuthenticationOptions>
{
public FeishuAuthenticationHandler(
[NotNull] IOptionsMonitor<FeishuAuthenticationOptions> 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 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);
}
}
31 changes: 31 additions & 0 deletions src/AspNet.Security.OAuth.Feishu/FeishuAuthenticationOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* 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.Feishu.FeishuAuthenticationConstants;

namespace AspNet.Security.OAuth.Feishu;

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

AuthorizationEndpoint = FeishuAuthenticationDefaults.AuthorizationEndpoint;
TokenEndpoint = FeishuAuthenticationDefaults.TokenEndpoint;
UserInformationEndpoint = FeishuAuthenticationDefaults.UserInformationEndpoint;

ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "open_id");
ClaimActions.MapJsonKey(ClaimTypes.Name, "name");
ClaimActions.MapJsonKey(Claims.UnionId, "union_id");
ClaimActions.MapJsonKey(Claims.Avatar, "avatar_big");
}
}
42 changes: 42 additions & 0 deletions test/AspNet.Security.OAuth.Providers.Tests/Feishu/FeishuTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
* 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.Feishu;

public class FeishuTests : OAuthTests<FeishuAuthenticationOptions>
{
public FeishuTests(ITestOutputHelper outputHelper)
{
OutputHelper = outputHelper;
}

public override string DefaultScheme => FeishuAuthenticationDefaults.AuthenticationScheme;

protected internal override void RegisterAuthentication(AuthenticationBuilder builder)
{
builder.AddFeishu(options =>
{
ConfigureDefaults(builder, options);
});
}

[Theory]
[InlineData(ClaimTypes.NameIdentifier, "test-open-id")]
[InlineData(ClaimTypes.Name, "test-name")]
[InlineData(FeishuAuthenticationConstants.Claims.UnionId, "test-union-id")]
[InlineData(FeishuAuthenticationConstants.Claims.Avatar, "https://www.feishu.cn/avatar/icon_big")]
public async Task Can_Sign_In_Using_Feishu(string claimType, string claimValue)
{
// Arrange
using var server = CreateTestServer();

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

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

0 comments on commit f1e2f76

Please sign in to comment.