-
Notifications
You must be signed in to change notification settings - Fork 540
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implement Airtable OAuth provider (#895)
Implement Airtable OAuth provider.
- Loading branch information
1 parent
3be27ad
commit b6c69ec
Showing
9 changed files
with
386 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
48 changes: 48 additions & 0 deletions
48
src/AspNet.Security.OAuth.Airtable/AirtableAuthenticationDefaults.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.Airtable; | ||
|
||
/// <summary> | ||
/// Default values used by the Airtable authentication middleware. | ||
/// </summary> | ||
public static class AirtableAuthenticationDefaults | ||
{ | ||
/// <summary> | ||
/// Default value for <see cref="AuthenticationScheme.Name"/>. | ||
/// </summary> | ||
public const string AuthenticationScheme = "Airtable"; | ||
|
||
/// <summary> | ||
/// Default value for <see cref="AuthenticationScheme.DisplayName"/>. | ||
/// </summary> | ||
public static readonly string DisplayName = "Airtable"; | ||
|
||
/// <summary> | ||
/// Default value for <see cref="AuthenticationSchemeOptions.ClaimsIssuer"/>. | ||
/// </summary> | ||
public static readonly string Issuer = "Airtable"; | ||
|
||
/// <summary> | ||
/// Default value for <see cref="RemoteAuthenticationOptions.CallbackPath"/>. | ||
/// </summary> | ||
public static readonly string CallbackPath = "/signin-airtable"; | ||
|
||
/// <summary> | ||
/// Default value for <see cref="OAuthOptions.AuthorizationEndpoint"/>. | ||
/// </summary> | ||
public static readonly string AuthorizationEndpoint = "https://airtable.com/oauth2/v1/authorize"; | ||
|
||
/// <summary> | ||
/// Default value for <see cref="OAuthOptions.TokenEndpoint"/>. | ||
/// </summary> | ||
public static readonly string TokenEndpoint = "https://airtable.com/oauth2/v1/token"; | ||
|
||
/// <summary> | ||
/// Default value for <see cref="OAuthOptions.UserInformationEndpoint"/>. | ||
/// </summary> | ||
public static readonly string UserInformationEndpoint = "https://api.airtable.com/v0/meta/whoami"; | ||
} |
74 changes: 74 additions & 0 deletions
74
src/AspNet.Security.OAuth.Airtable/AirtableAuthenticationExtensions.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 Microsoft.Extensions.DependencyInjection; | ||
|
||
namespace AspNet.Security.OAuth.Airtable; | ||
|
||
/// <summary> | ||
/// Extension methods to add Airtable authentication capabilities to an HTTP application pipeline. | ||
/// </summary> | ||
public static class AirtableAuthenticationExtensions | ||
{ | ||
/// <summary> | ||
/// Adds <see cref="AirtableAuthenticationHandler"/> to the specified | ||
/// <see cref="AuthenticationBuilder"/>, which enables Airtable 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 AddAirtable([NotNull] this AuthenticationBuilder builder) | ||
{ | ||
return builder.AddAirtable(AirtableAuthenticationDefaults.AuthenticationScheme, options => { }); | ||
} | ||
|
||
/// <summary> | ||
/// Adds <see cref="AirtableAuthenticationHandler"/> to the specified | ||
/// <see cref="AuthenticationBuilder"/>, which enables Airtable 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 AddAirtable( | ||
[NotNull] this AuthenticationBuilder builder, | ||
[NotNull] Action<AirtableAuthenticationOptions> configuration) | ||
{ | ||
return builder.AddAirtable(AirtableAuthenticationDefaults.AuthenticationScheme, configuration); | ||
} | ||
|
||
/// <summary> | ||
/// Adds <see cref="AirtableAuthenticationHandler"/> to the specified | ||
/// <see cref="AuthenticationBuilder"/>, which enables Airtable 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 Airtable options.</param> | ||
/// <returns>The <see cref="AuthenticationBuilder"/>.</returns> | ||
public static AuthenticationBuilder AddAirtable( | ||
[NotNull] this AuthenticationBuilder builder, | ||
[NotNull] string scheme, | ||
[NotNull] Action<AirtableAuthenticationOptions> configuration) | ||
{ | ||
return builder.AddAirtable(scheme, AirtableAuthenticationDefaults.DisplayName, configuration); | ||
} | ||
|
||
/// <summary> | ||
/// Adds <see cref="AirtableAuthenticationHandler"/> to the specified | ||
/// <see cref="AuthenticationBuilder"/>, which enables Airtable 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 Airtable options.</param> | ||
/// <returns>The <see cref="AuthenticationBuilder"/>.</returns> | ||
public static AuthenticationBuilder AddAirtable( | ||
[NotNull] this AuthenticationBuilder builder, | ||
[NotNull] string scheme, | ||
[CanBeNull] string caption, | ||
[NotNull] Action<AirtableAuthenticationOptions> configuration) | ||
{ | ||
return builder.AddOAuth<AirtableAuthenticationOptions, AirtableAuthenticationHandler>(scheme, caption, configuration); | ||
} | ||
} |
150 changes: 150 additions & 0 deletions
150
src/AspNet.Security.OAuth.Airtable/AirtableAuthenticationHandler.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,150 @@ | ||
/* | ||
* 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; | ||
using System.Net.Http.Headers; | ||
using System.Net.Mime; | ||
using System.Security.Claims; | ||
using System.Text; | ||
using System.Text.Encodings.Web; | ||
using System.Text.Json; | ||
using Microsoft.Extensions.Logging; | ||
using Microsoft.Extensions.Options; | ||
|
||
namespace AspNet.Security.OAuth.Airtable; | ||
|
||
public partial class AirtableAuthenticationHandler : OAuthHandler<AirtableAuthenticationOptions> | ||
{ | ||
public AirtableAuthenticationHandler( | ||
[NotNull] IOptionsMonitor<AirtableAuthenticationOptions> options, | ||
[NotNull] ILoggerFactory logger, | ||
[NotNull] UrlEncoder encoder) | ||
: base(options, logger, encoder) | ||
{ | ||
} | ||
|
||
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); | ||
} | ||
|
||
protected override async Task<OAuthTokenResponse> ExchangeCodeAsync([NotNull]OAuthCodeExchangeContext context) | ||
{ | ||
var tokenRequestParameters = new Dictionary<string, string> | ||
{ | ||
{ "client_id", Options.ClientId }, | ||
{ "redirect_uri", context.RedirectUri }, | ||
{ "client_secret", Options.ClientSecret }, | ||
{ "code", context.Code }, | ||
{ "grant_type", "authorization_code" } | ||
}; | ||
|
||
// PKCE https://tools.ietf.org/html/rfc7636#section-4.5, see BuildChallengeUrl | ||
if (context.Properties.Items.TryGetValue(OAuthConstants.CodeVerifierKey, out var codeVerifier)) | ||
{ | ||
tokenRequestParameters.Add(OAuthConstants.CodeVerifierKey, codeVerifier!); | ||
context.Properties.Items.Remove(OAuthConstants.CodeVerifierKey); | ||
} | ||
|
||
using var requestMessage = new HttpRequestMessage(HttpMethod.Post, Options.TokenEndpoint); | ||
requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaTypeNames.Application.Json)); | ||
requestMessage.Content = new FormUrlEncodedContent(tokenRequestParameters); | ||
requestMessage.Headers.Authorization = CreateAuthorizationHeader(); | ||
requestMessage.Version = Backchannel.DefaultRequestVersion; | ||
|
||
var response = await Backchannel.SendAsync(requestMessage, Context.RequestAborted); | ||
var body = await response.Content.ReadAsStringAsync(Context.RequestAborted); | ||
|
||
return response.IsSuccessStatusCode switch | ||
{ | ||
true => OAuthTokenResponse.Success(JsonDocument.Parse(body)), | ||
false => await ParseInvalidResponseAsync(response) | ||
}; | ||
} | ||
|
||
private AuthenticationHeaderValue CreateAuthorizationHeader() | ||
{ | ||
var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes( | ||
string.Concat( | ||
EscapeDataString(Options.ClientId), | ||
":", | ||
EscapeDataString(Options.ClientSecret)))); | ||
|
||
return new AuthenticationHeaderValue("Basic", credentials); | ||
} | ||
|
||
private static string EscapeDataString(string value) | ||
{ | ||
if (string.IsNullOrEmpty(value)) | ||
{ | ||
return string.Empty; | ||
} | ||
|
||
return Uri.EscapeDataString(value).Replace("%20", "+", StringComparison.Ordinal); | ||
} | ||
|
||
private async Task<OAuthTokenResponse> ParseInvalidResponseAsync(HttpResponseMessage response) | ||
{ | ||
await Log.ExchangeCodeErrorAsync(Logger, response, Context.RequestAborted); | ||
return OAuthTokenResponse.Failed(new Exception("An error occurred while retrieving an access token.")); | ||
} | ||
|
||
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)); | ||
} | ||
|
||
internal static async Task ExchangeCodeErrorAsync(ILogger logger, HttpResponseMessage response, CancellationToken cancellationToken) | ||
{ | ||
ExchangeCodeError( | ||
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 an access token: the remote server returned a {Status} response with the following payload: {Headers} {Body}.")] | ||
private static partial void ExchangeCodeError( | ||
ILogger logger, | ||
HttpStatusCode status, | ||
string headers, | ||
string body); | ||
} | ||
} |
30 changes: 30 additions & 0 deletions
30
src/AspNet.Security.OAuth.Airtable/AirtableAuthenticationOptions.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
/* | ||
* 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.Airtable; | ||
|
||
/// <summary> | ||
/// Defines a set of options used by <see cref="AirtableAuthenticationHandler"/>. | ||
/// </summary> | ||
public class AirtableAuthenticationOptions : OAuthOptions | ||
{ | ||
public AirtableAuthenticationOptions() | ||
{ | ||
ClaimsIssuer = AirtableAuthenticationDefaults.Issuer; | ||
CallbackPath = AirtableAuthenticationDefaults.CallbackPath; | ||
|
||
AuthorizationEndpoint = AirtableAuthenticationDefaults.AuthorizationEndpoint; | ||
TokenEndpoint = AirtableAuthenticationDefaults.TokenEndpoint; | ||
UserInformationEndpoint = AirtableAuthenticationDefaults.UserInformationEndpoint; | ||
|
||
Scope.Add("user.email:read"); | ||
|
||
ClaimActions.MapCustomJson(ClaimTypes.NameIdentifier, user => user.GetString("id")); | ||
ClaimActions.MapCustomJson(ClaimTypes.Email, user => user.GetString("email")); | ||
} | ||
} |
24 changes: 24 additions & 0 deletions
24
src/AspNet.Security.OAuth.Airtable/AspNet.Security.OAuth.Airtable.csproj
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
<PropertyGroup> | ||
<TargetFramework>$(DefaultNetCoreTargetFramework)</TargetFramework> | ||
</PropertyGroup> | ||
|
||
<!-- TODO Enable once this provider is published to NuGet.org --> | ||
<PropertyGroup> | ||
<DisablePackageBaselineValidation>true</DisablePackageBaselineValidation> | ||
<PackageValidationBaselineVersion>8.0.1</PackageValidationBaselineVersion> | ||
</PropertyGroup> | ||
|
||
<PropertyGroup> | ||
<Description>ASP.NET Core security middleware enabling Airtable authentication.</Description> | ||
<Authors>Denys Goncharenko</Authors> | ||
<PackageTags>aspnetcore;authentication;oauth;airtable;security</PackageTags> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<FrameworkReference Include="Microsoft.AspNetCore.App"/> | ||
<PackageReference Include="JetBrains.Annotations" PrivateAssets="All"/> | ||
</ItemGroup> | ||
|
||
</Project> |
Oops, something went wrong.