-
Notifications
You must be signed in to change notification settings - Fork 547
Adds Contentful provider #1063
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
Merged
martincostello
merged 3 commits into
aspnet-contrib:dev
from
jerriep:add-contentful-provider
May 1, 2025
Merged
Adds Contentful provider #1063
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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 hidden or 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 hidden or 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,20 @@ | ||
| # Integrating the Contentful Provider | ||
|
|
||
| ## Example | ||
|
|
||
| ```csharp | ||
| services.AddAuthentication(options => /* Auth configuration */) | ||
| .AddContentful(options => | ||
| { | ||
| options.ClientId = "my-client-id"; | ||
| options.ClientSecret = "my-client-secret"; | ||
| }); | ||
| ``` | ||
|
|
||
| ## Required Additional Settings | ||
|
|
||
| _None._ | ||
|
|
||
| ## Optional Settings | ||
|
|
||
| _None._ |
18 changes: 18 additions & 0 deletions
18
src/AspNet.Security.OAuth.Contentful/AspNet.Security.OAuth.Contentful.csproj
This file contains hidden or 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,18 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <TargetFramework>$(DefaultNetCoreTargetFramework)</TargetFramework> | ||
| </PropertyGroup> | ||
|
|
||
| <PropertyGroup> | ||
| <Description>ASP.NET Core security middleware enabling Contentful authentication.</Description> | ||
| <Authors>Jerrie Pelser</Authors> | ||
| <PackageTags>contentful;aspnetcore;authentication;oauth;security</PackageTags> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <FrameworkReference Include="Microsoft.AspNetCore.App" /> | ||
| <PackageReference Include="JetBrains.Annotations" PrivateAssets="All" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
48 changes: 48 additions & 0 deletions
48
src/AspNet.Security.OAuth.Contentful/ContentfulAuthenticationDefaults.cs
This file contains hidden or 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.Contentful; | ||
|
|
||
| /// <summary> | ||
| /// Default values used by the Contentful authentication middleware. | ||
| /// </summary> | ||
| public static class ContentfulAuthenticationDefaults | ||
| { | ||
| /// <summary> | ||
| /// Default value for the <see cref="AuthenticationScheme.Name"/>. | ||
| /// </summary> | ||
| public const string AuthenticationScheme = "Contentful"; | ||
|
|
||
| /// <summary> | ||
| /// Default value for the <see cref="AuthenticationScheme.DisplayName"/>. | ||
| /// </summary> | ||
| public static readonly string DisplayName = "Contentful"; | ||
|
|
||
| /// <summary> | ||
| /// Default value for the <see cref="AuthenticationSchemeOptions.ClaimsIssuer"/>. | ||
| /// </summary> | ||
| public static readonly string Issuer = "Contentful"; | ||
|
|
||
| /// <summary> | ||
| /// Default value for the <see cref="RemoteAuthenticationOptions.CallbackPath"/>. | ||
| /// </summary> | ||
| public static readonly string CallbackPath = "/signin-contentful"; | ||
|
|
||
| /// <summary> | ||
| /// Default value for the <see cref="OAuthOptions.AuthorizationEndpoint"/>. | ||
| /// </summary> | ||
| public static readonly string AuthorizationEndpoint = "https://be.contentful.com/oauth/authorize"; | ||
|
|
||
| /// <summary> | ||
| /// Default value for the <see cref="OAuthOptions.TokenEndpoint"/>. | ||
| /// </summary> | ||
| public static readonly string TokenEndpointFormat = "https://be.contentful.com/oauth/token"; | ||
|
|
||
| /// <summary> | ||
| /// Default value for <see cref="OAuthOptions.UserInformationEndpoint"/>. | ||
| /// </summary> | ||
| public static readonly string UserInformationEndpoint = "https://api.contentful.com/users/me"; | ||
| } |
71 changes: 71 additions & 0 deletions
71
src/AspNet.Security.OAuth.Contentful/ContentfulAuthenticationExtensions.cs
This file contains hidden or 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,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 AspNet.Security.OAuth.Contentful; | ||
|
|
||
| namespace Microsoft.Extensions.DependencyInjection; | ||
|
|
||
| public static class ContentfulAuthenticationExtensions | ||
| { | ||
| /// <summary> | ||
| /// Adds <see cref="ContentfulAuthenticationHandler"/> to the specified | ||
| /// <see cref="AuthenticationBuilder"/>, which enables Contentful 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 AddContentful([NotNull] this AuthenticationBuilder builder) | ||
| { | ||
| return builder.AddContentful(ContentfulAuthenticationDefaults.AuthenticationScheme, options => { }); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Adds <see cref="ContentfulAuthenticationHandler"/> to the specified | ||
| /// <see cref="AuthenticationBuilder"/>, which enables Contentful authentication capabilities. | ||
| /// </summary> | ||
| /// <param name="builder">The authentication builder.</param> | ||
| /// <param name="configuration">The delegate used to configure the Contentful options.</param> | ||
| /// <returns>A reference to this instance after the operation has completed.</returns> | ||
| public static AuthenticationBuilder AddContentful( | ||
| [NotNull] this AuthenticationBuilder builder, | ||
| [NotNull] Action<ContentfulAuthenticationOptions> configuration) | ||
| { | ||
| return builder.AddContentful(ContentfulAuthenticationDefaults.AuthenticationScheme, configuration); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Adds <see cref="ContentfulAuthenticationHandler"/> to the specified | ||
| /// <see cref="AuthenticationBuilder"/>, which enables Contentful 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 Contentful options.</param> | ||
| /// <returns>The <see cref="AuthenticationBuilder"/>.</returns> | ||
| public static AuthenticationBuilder AddContentful( | ||
| [NotNull] this AuthenticationBuilder builder, | ||
| [NotNull] string scheme, | ||
| [NotNull] Action<ContentfulAuthenticationOptions> configuration) | ||
| { | ||
| return builder.AddContentful(scheme, ContentfulAuthenticationDefaults.DisplayName, configuration); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Adds <see cref="ContentfulAuthenticationHandler"/> to the specified | ||
| /// <see cref="AuthenticationBuilder"/>, which enables Contentful 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 Contentful options.</param> | ||
| /// <returns>The <see cref="AuthenticationBuilder"/>.</returns> | ||
| public static AuthenticationBuilder AddContentful( | ||
| [NotNull] this AuthenticationBuilder builder, | ||
| [NotNull] string scheme, | ||
| [NotNull] string caption, | ||
| [NotNull] Action<ContentfulAuthenticationOptions> configuration) | ||
| { | ||
| return builder.AddOAuth<ContentfulAuthenticationOptions, ContentfulAuthenticationHandler>(scheme, caption, configuration); | ||
| } | ||
| } |
75 changes: 75 additions & 0 deletions
75
src/AspNet.Security.OAuth.Contentful/ContentfulAuthenticationHandler.cs
This file contains hidden or 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,75 @@ | ||
| /* | ||
| * 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.Contentful; | ||
|
|
||
| public partial class ContentfulAuthenticationHandler( | ||
| [NotNull] IOptionsMonitor<ContentfulAuthenticationOptions> options, | ||
| [NotNull] ILoggerFactory logger, | ||
| [NotNull] UrlEncoder encoder) : OAuthHandler<ContentfulAuthenticationOptions>(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 from Contentful."); | ||
| } | ||
|
|
||
| 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); | ||
| } | ||
| } |
30 changes: 30 additions & 0 deletions
30
src/AspNet.Security.OAuth.Contentful/ContentfulAuthenticationOptions.cs
This file contains hidden or 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.Contentful; | ||
|
|
||
| /// <summary> | ||
| /// Defines a set of options used by <see cref="ContentfulAuthenticationHandler"/>. | ||
| /// </summary> | ||
| public class ContentfulAuthenticationOptions : OAuthOptions | ||
| { | ||
| public ContentfulAuthenticationOptions() | ||
| { | ||
| ClaimsIssuer = ContentfulAuthenticationDefaults.Issuer; | ||
| CallbackPath = ContentfulAuthenticationDefaults.CallbackPath; | ||
|
|
||
| AuthorizationEndpoint = ContentfulAuthenticationDefaults.AuthorizationEndpoint; | ||
| TokenEndpoint = ContentfulAuthenticationDefaults.TokenEndpointFormat; | ||
| UserInformationEndpoint = ContentfulAuthenticationDefaults.UserInformationEndpoint; | ||
|
|
||
| ClaimActions.MapJsonSubKey(ClaimTypes.NameIdentifier, "sys", "id"); | ||
| ClaimActions.MapJsonKey(ClaimTypes.Email, "email"); | ||
| ClaimActions.MapJsonKey(ClaimTypes.GivenName, "firstName"); | ||
| ClaimActions.MapJsonKey(ClaimTypes.Surname, "lastName"); | ||
| } | ||
| } |
25 changes: 25 additions & 0 deletions
25
test/AspNet.Security.OAuth.Providers.Tests/Contentful/ContentfulTests.cs
This file contains hidden or 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,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.Contentful; | ||
|
|
||
| public class ContentfulTests(ITestOutputHelper outputHelper) : OAuthTests<ContentfulAuthenticationOptions>(outputHelper) | ||
| { | ||
| public override string DefaultScheme => ContentfulAuthenticationDefaults.AuthenticationScheme; | ||
|
|
||
| protected internal override void RegisterAuthentication(AuthenticationBuilder builder) | ||
| { | ||
| builder.AddContentful(options => ConfigureDefaults(builder, options)); | ||
| } | ||
|
|
||
| [Theory] | ||
| [InlineData(ClaimTypes.NameIdentifier, "user-id")] | ||
| [InlineData(ClaimTypes.Email, "some@email.com")] | ||
| [InlineData(ClaimTypes.GivenName, "Some")] | ||
| [InlineData(ClaimTypes.Surname, "One")] | ||
| public async Task Can_Sign_In_Using_Contentful(string claimType, string claimValue) | ||
| => await AuthenticateUserAndAssertClaimValue(claimType, claimValue); | ||
| } |
38 changes: 38 additions & 0 deletions
38
test/AspNet.Security.OAuth.Providers.Tests/Contentful/bundle.json
This file contains hidden or 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,38 @@ | ||
| { | ||
| "$schema": "https://raw.githubusercontent.com/justeat/httpclient-interception/master/src/HttpClientInterception/Bundles/http-request-bundle-schema.json", | ||
| "items": [ | ||
| { | ||
| "uri": "https://be.contentful.com/oauth/token", | ||
| "method": "POST", | ||
| "contentFormat": "json", | ||
| "contentJson": { | ||
| "access_token": "secret-access-token", | ||
| "token_type": "Bearer", | ||
| "refresh_token": "secret-refresh-token", | ||
| "scope": "content_management_read" | ||
| } | ||
| }, | ||
| { | ||
| "uri": "https://api.contentful.com/users/me", | ||
| "contentFormat": "json", | ||
| "contentJson": { | ||
| "firstName": "Some", | ||
| "lastName": "One", | ||
| "avatarUrl": "https://gravatar.com/avatar/27205e5c51cb03f862138b22bcb5dc20f94a342e744ff6df1b8dc8af3c865109", | ||
| "email": "some@email.com", | ||
| "signupSource": null, | ||
| "activated": true, | ||
| "signInCount": 475, | ||
| "confirmed": true, | ||
| "2faEnabled": false, | ||
| "sys": { | ||
| "type": "User", | ||
| "id": "user-id", | ||
| "version": 490, | ||
| "createdAt": "2018-08-15T04:08:47Z", | ||
| "updatedAt": "2025-05-01T03:09:46Z" | ||
| } | ||
| } | ||
| } | ||
| ] | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.