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

Added JumpCloud support #797

Merged
merged 10 commits into from
Aug 15, 2023
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
martincostello marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">

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

<PropertyGroup>
<Description>ASP.NET Core security middleware enabling JumpCloud authentication.</Description>
<Authors>AaronSadlerUK</Authors>
<PackageTags>jumpcloud;aspnetcore;authentication;oauth;security</PackageTags>
</PropertyGroup>

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

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

namespace AspNet.Security.OAuth.JumpCloud;

/// <summary>
/// Default values used by the JumpCloud authentication provider.
/// </summary>
public static class JumpCloudAuthenticationDefaults
{
/// <summary>
/// Default value for <see cref="AuthenticationScheme.Name"/>.
/// </summary>
public const string AuthenticationScheme = "JumpCloud";

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

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

/// <summary>
/// The name of the default JumpCloud custom Authorization Server.
/// </summary>
public static readonly string DefaultAuthorizationServer = "default";

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

/// <summary>
/// Default path format to use for <see cref="OAuthOptions.AuthorizationEndpoint"/>.
/// </summary>
public static readonly string AuthorizationEndpointPathFormat = "/oauth2/auth";

/// <summary>
/// Default path format to use for <see cref="OAuthOptions.TokenEndpoint"/>.
/// </summary>
public static readonly string TokenEndpointPathFormat = "/oauth2/token";

/// <summary>
/// Default path format to use for <see cref="OAuthOptions.UserInformationEndpoint"/>.
/// </summary>
public static readonly string UserInformationEndpointPathFormat = "/userinfo";

/// <summary>
/// Default path to use for <see cref="OAuthOptions.AuthorizationEndpoint"/>.
/// </summary>
public static readonly string AuthorizationEndpointPath = string.Format(CultureInfo.InvariantCulture, AuthorizationEndpointPathFormat, DefaultAuthorizationServer);

/// <summary>
/// Default path to use for <see cref="OAuthOptions.TokenEndpoint"/>.
/// </summary>
public static readonly string TokenEndpointPath = string.Format(CultureInfo.InvariantCulture, TokenEndpointPathFormat, DefaultAuthorizationServer);

/// <summary>
/// Default path to use for <see cref="OAuthOptions.UserInformationEndpoint"/>.
/// </summary>
public static readonly string UserInformationEndpointPath = string.Format(CultureInfo.InvariantCulture, UserInformationEndpointPathFormat, DefaultAuthorizationServer);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/*
* 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.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;

namespace AspNet.Security.OAuth.JumpCloud;

/// <summary>
/// Extension methods to add JumpCloud authentication capabilities to an HTTP application pipeline.
/// </summary>
public static class JumpCloudAuthenticationExtensions
{
/// <summary>
/// Adds <see cref="AspNet.Security.OAuth.JumpCloud.JumpCloudAuthenticationHandler"/> to the specified
/// <see cref="AuthenticationBuilder"/>, which enables JumpCloud authentication capabilities.
/// </summary>
/// <param name="builder">The authentication builder.</param>
/// <returns>The <see cref="AuthenticationBuilder"/>.</returns>
public static AuthenticationBuilder AddJumpCloud([NotNull] this AuthenticationBuilder builder)
{
return builder.AddJumpCloud(JumpCloudAuthenticationDefaults.AuthenticationScheme, options => { });
}

/// <summary>
/// Adds <see cref="AspNet.Security.OAuth.JumpCloud.JumpCloudAuthenticationHandler"/> to the specified
/// <see cref="AuthenticationBuilder"/>, which enables JumpCloud authentication capabilities.
/// </summary>
/// <param name="builder">The authentication builder.</param>
/// <param name="configuration">The delegate used to configure the JumpCloud options.</param>
/// <returns>The <see cref="AuthenticationBuilder"/>.</returns>
public static AuthenticationBuilder AddJumpCloud(
[NotNull] this AuthenticationBuilder builder,
[NotNull] Action<JumpCloudAuthenticationOptions> configuration)
{
return builder.AddJumpCloud(JumpCloudAuthenticationDefaults.AuthenticationScheme, configuration);
}

/// <summary>
/// Adds <see cref="AspNet.Security.OAuth.JumpCloud.JumpCloudAuthenticationHandler"/> to the specified
/// <see cref="AuthenticationBuilder"/>, which enables JumpCloud 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 JumpCloud options.</param>
/// <returns>The <see cref="AuthenticationBuilder"/>.</returns>
public static AuthenticationBuilder AddJumpCloud(
[NotNull] this AuthenticationBuilder builder,
[NotNull] string scheme,
[NotNull] Action<JumpCloudAuthenticationOptions> configuration)
{
return builder.AddJumpCloud(scheme, JumpCloudAuthenticationDefaults.DisplayName, configuration);
}

/// <summary>
/// Adds <see cref="AspNet.Security.OAuth.JumpCloud.JumpCloudAuthenticationHandler"/> to the specified
/// <see cref="AuthenticationBuilder"/>, which enables JumpCloud 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 JumpCloud options.</param>
/// <returns>The <see cref="AuthenticationBuilder"/>.</returns>
public static AuthenticationBuilder AddJumpCloud(
[NotNull] this AuthenticationBuilder builder,
[NotNull] string scheme,
string? caption,
[NotNull] Action<JumpCloudAuthenticationOptions> configuration)
{
builder.Services.TryAddSingleton<IPostConfigureOptions<JumpCloudAuthenticationOptions>, JumpCloudPostConfigureOptions>();
return builder.AddOAuth<JumpCloudAuthenticationOptions, AspNet.Security.OAuth.JumpCloud.JumpCloudAuthenticationHandler>(scheme, caption, configuration);
}
}
84 changes: 84 additions & 0 deletions AspNet.Security.OAuth.JumpCloud/JumpCloudAuthenticationHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/*
* 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.JumpCloud;

/// <summary>
/// Defines a handler for authentication using JumpCloud.
/// </summary>
public partial class JumpCloudAuthenticationHandler : OAuthHandler<JumpCloudAuthenticationOptions>
{
/// <summary>
/// Initializes a new instance of the <see cref="JumpCloudAuthenticationHandler"/> class.
/// </summary>
/// <param name="options">The authentication options.</param>
/// <param name="logger">The logger to use.</param>
/// <param name="encoder">The URL encoder to use.</param>
/// <param name="clock">The system clock to use.</param>
public JumpCloudAuthenticationHandler(
[NotNull] IOptionsMonitor<JumpCloudAuthenticationOptions> options,
[NotNull] ILoggerFactory logger,
[NotNull] UrlEncoder encoder,
[NotNull] ISystemClock clock)
: base(options, logger, encoder, clock)
{
}

/// <inheritdoc />
protected override async Task<AuthenticationTicket> CreateTicketAsync(
[NotNull] ClaimsIdentity identity,
[NotNull] AuthenticationProperties properties,
[NotNull] OAuthTokenResponse tokens)
{
string endpoint = Options.UserInformationEndpoint;

using var request = new HttpRequestMessage(HttpMethod.Get, endpoint);
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 from JumpCloud.");
}

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);
}
}
74 changes: 74 additions & 0 deletions AspNet.Security.OAuth.JumpCloud/JumpCloudAuthenticationOptions.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 System.Security.Claims;

namespace AspNet.Security.OAuth.JumpCloud;

/// <summary>
/// Defines a set of options used by <see cref="JumpCloudAuthenticationHandler"/>.
/// </summary>
public class JumpCloudAuthenticationOptions : OAuthOptions
{
/// <summary>
/// Initializes a new instance of the <see cref="JumpCloudAuthenticationOptions"/> class.
/// </summary>
public JumpCloudAuthenticationOptions()
{
ClaimsIssuer = JumpCloudAuthenticationDefaults.Issuer;
CallbackPath = JumpCloudAuthenticationDefaults.CallbackPath;

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

ClaimActions.MapJsonKey(ClaimTypes.Email, "email");
ClaimActions.MapJsonKey(ClaimTypes.GivenName, "given_name");
ClaimActions.MapJsonKey(ClaimTypes.Name, "name");
ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "sub");
ClaimActions.MapJsonKey(ClaimTypes.Surname, "family_name");
}

/// <summary>
/// Gets or sets the JumpCloud custom authorization server to use for authentication.
/// </summary>
/// <remarks>
/// The default value is <c>default</c>.
/// </remarks>
public string AuthorizationServer { get; set; } = JumpCloudAuthenticationDefaults.DefaultAuthorizationServer;

/// <summary>
/// Gets or sets the JumpCloud domain (Org URL) to use for authentication.
/// </summary>
public string? Domain { get; set; }

/// <inheritdoc/>
public override void Validate()
{
base.Validate();

if (!Uri.TryCreate(AuthorizationEndpoint, UriKind.Absolute, out _))
{
throw new ArgumentException(
$"The '{nameof(AuthorizationEndpoint)}' option must be set to a valid URI.",
nameof(AuthorizationEndpoint));
}

if (!Uri.TryCreate(TokenEndpoint, UriKind.Absolute, out _))
{
throw new ArgumentException(
$"The '{nameof(TokenEndpoint)}' option must be set to a valid URI.",
nameof(TokenEndpoint));
}

if (!Uri.TryCreate(UserInformationEndpoint, UriKind.Absolute, out _))
{
throw new ArgumentException(
$"The '{nameof(UserInformationEndpoint)}' option must be set to a valid URI.",
nameof(UserInformationEndpoint));
}
}
}
51 changes: 51 additions & 0 deletions AspNet.Security.OAuth.JumpCloud/JumpCloudPostConfigureOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* 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.Globalization;
using Microsoft.Extensions.Options;

namespace AspNet.Security.OAuth.JumpCloud;

/// <summary>
/// A class used to setup defaults for all <see cref="JumpCloudAuthenticationOptions"/>.
/// </summary>
public class JumpCloudPostConfigureOptions : IPostConfigureOptions<JumpCloudAuthenticationOptions>
{
/// <inheritdoc/>
public void PostConfigure(
string? name,
[NotNull] JumpCloudAuthenticationOptions options)
{
if (string.IsNullOrWhiteSpace(options.Domain))
{
throw new ArgumentException("No JumpCloud domain configured.", nameof(options));
}

if (string.IsNullOrWhiteSpace(options.AuthorizationServer))
{
throw new ArgumentException("No JumpCloud authorization server configured.", nameof(options));
}

options.AuthorizationEndpoint = CreateUrl(options.Domain, JumpCloudAuthenticationDefaults.AuthorizationEndpointPathFormat, options.AuthorizationServer);
options.TokenEndpoint = CreateUrl(options.Domain, JumpCloudAuthenticationDefaults.TokenEndpointPathFormat, options.AuthorizationServer);
options.UserInformationEndpoint = CreateUrl(options.Domain, JumpCloudAuthenticationDefaults.UserInformationEndpointPathFormat, options.AuthorizationServer);
}

private static string CreateUrl(string domain, string pathFormat, params object[] args)
{
var path = string.Format(CultureInfo.InvariantCulture, pathFormat, args);

// Enforce use of HTTPS
var builder = new UriBuilder(domain)
{
Path = path,
Port = -1,
Scheme = Uri.UriSchemeHttps,
};

return builder.Uri.ToString();
}
}
Loading