Skip to content

Commit

Permalink
Issue 44 pkce configuration (#45)
Browse files Browse the repository at this point in the history
#44 complete
  • Loading branch information
Calabonga authored Dec 13, 2024
2 parents 95c4766 + a345316 commit f582730
Show file tree
Hide file tree
Showing 13 changed files with 116 additions and 25 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<!-- The package metadata. Fill in the properties marked as TODO below -->
<!-- Follow the instructions on https://learn.microsoft.com/en-us/nuget/create-packages/package-authoring-best-practices -->
<PackageId>Calabonga.Microservice.IdentityModule.Template</PackageId>
<PackageVersion>9.0.0</PackageVersion>
<PackageVersion>9.0.1</PackageVersion>
<Title>Microservice template with OpenIddict</Title>
<Authors>Calabonga</Authors>
<Copyright>Calabonga SOFT © 2019 - $([System.DateTime]::Now.ToString(yyyy))</Copyright>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="OpenIddict.AspNetCore" Version="5.8.0" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.3" />
<PackageReference Include="Serilog.AspNetCore" Version="9.0.0" />
<PackageReference Include="Serilog.Formatting.Compact" Version="3.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="7.1.0" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="7.2.0" />
<PackageReference Include="System.Linq.Async" Version="6.0.1" />
</ItemGroup>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public class OpenApiDefinition : AppDefinition
// Otherwise, you can change versions of your API by manually.
// If you are not going to use git-versioning, do not forget install package "GitInfo"
// private const string AppVersion = $"{ThisAssembly.Git.SemVer.Major}.{ThisAssembly.Git.SemVer.Minor}.{ThisAssembly.Git.SemVer.Patch}";
public const string AppVersion = "9.0.0";
public const string AppVersion = "9.0.1";

private const string _openApiConfig = "/openapi/v1.json";

Expand Down Expand Up @@ -57,6 +57,7 @@ public override void ConfigureApplication(WebApplication app)
settings.OAuthClientId("client-id-code");
settings.OAuthClientSecret("client-secret-code");
settings.DisplayRequestDuration();
settings.OAuthUsePkce();
settings.OAuthAppName(AppData.ServiceName);
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public override void ConfigureServices(WebApplicationBuilder builder)
// => Password flow
// => Refresh token flow
options
.AllowAuthorizationCodeFlow()//.RequireProofKeyForCodeExchange()
.AllowAuthorizationCodeFlow().RequireProofKeyForCodeExchange()
.AllowPasswordFlow()
.AllowClientCredentialsFlow()
.AllowRefreshTokenFlow();
Expand All @@ -50,10 +50,9 @@ public override void ConfigureServices(WebApplicationBuilder builder)
// => options.SetRefreshTokenLifetime(TimeSpan.FromDays(7));

// Enable the token endpoint.
options.SetAuthorizationEndpointUris("connect/authorize")
//.RequireProofKeyForCodeExchange() // enable PKCE
//.SetDeviceEndpointUris("connect/device")
//.SetIntrospectionEndpointUris("connect/introspect")
options.SetAuthorizationEndpointUris("connect/authorize").RequireProofKeyForCodeExchange() // enable PKCE
//.SetDeviceEndpointUris("connect/device")
.SetIntrospectionEndpointUris("connect/introspect")
.SetLogoutEndpointUris("connect/logout")
.SetTokenEndpointUris("connect/token")
//.SetVerificationEndpointUris("connect/verify"),
Expand Down Expand Up @@ -81,12 +80,13 @@ public override void ConfigureServices(WebApplicationBuilder builder)
// Register the ASP.NET Core host and configure the ASP.NET Core options.
options
.UseAspNetCore()
//.DisableTransportSecurityRequirement() // disable HTTPS
.EnableLogoutEndpointPassthrough()
.EnableTokenEndpointPassthrough()
.EnableAuthorizationEndpointPassthrough();
.EnableAuthorizationEndpointPassthrough()
.DisableTransportSecurityRequirement();

//JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
//JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();
// JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
// JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();

//options.AddEventHandler<OpenIddictServerEvents.ProcessSignInContext>(builder =>
//{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,14 +51,19 @@ await manager.CreateAsync(new OpenIddictApplicationDescriptor
DisplayName = "API testing clients with Authorization Code Flow demonstration",
RedirectUris = {
new Uri("https://www.thunderclient.com/oauth/callback"), // https://www.thunderclient.com/
new Uri($"{url}/swagger/oauth2-redirect.html"), // https://swagger.io/
new Uri($"{url}/swagger/oauth2-redirect.html"), // https://swagger.io/ for IdentityModule as Example
new Uri("https://localhost:20001/swagger/oauth2-redirect.html") // https://swagger.io/ for Module as Example
},

PostLogoutRedirectUris =
{
new Uri("https://localhost:7207/signout-callback-oidc")
},
Permissions =
{
// Endpoint permissions
OpenIddictConstants.Permissions.Endpoints.Authorization,
OpenIddictConstants.Permissions.Endpoints.Logout,
OpenIddictConstants.Permissions.Endpoints.Introspection,
OpenIddictConstants.Permissions.Endpoints.Token,

// Grant type permissions
Expand All @@ -68,6 +73,9 @@ await manager.CreateAsync(new OpenIddictApplicationDescriptor
// Scope permissions
OpenIddictConstants.Permissions.Prefixes.Scope + "api",
OpenIddictConstants.Permissions.Prefixes.Scope + "custom",
OpenIddictConstants.Permissions.Scopes.Email,
OpenIddictConstants.Permissions.Scopes.Profile,
OpenIddictConstants.Permissions.Scopes.Roles,

// Response types
OpenIddictConstants.Permissions.ResponseTypes.Code,
Expand All @@ -78,4 +86,4 @@ await manager.CreateAsync(new OpenIddictApplicationDescriptor
}

public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
@page
@using Microsoft.AspNetCore.Mvc.TagHelpers
@using Microsoft.Extensions.Primitives
@model Calabonga.Microservice.IdentityModule.Web.Pages.Connect.LogoutModel
@{
var items = HttpContext.Request.HasFormContentType
? (IEnumerable<KeyValuePair<string, StringValues>>)HttpContext.Request.Form
: HttpContext.Request.Query;
}
<div class="col-md-4 offset-4 text-center">

<p class="lead">Are you sure you want to exit?</p>

<form method="post">

@foreach (var parameter in items)
{
<input type="hidden" name="@parameter.Key" value="@parameter.Value" />
}

<input class="btn btn-lg btn-success" name="Confirm" type="submit" value="Yes" />

</form>

</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using OpenIddict.Client.AspNetCore;
using OpenIddict.Server.AspNetCore;

namespace Calabonga.Microservice.IdentityModule.Web.Pages.Connect;

public class LogoutModel : PageModel
{
public void OnGet()
{
}

public async Task<IActionResult> OnPost(string returnUrl)
{
// Retrieve the identity stored in the local authentication cookie. If it's not available,
// this indicate that the user is already logged out locally (or has not logged in yet).
//
// For scenarios where the default authentication handler configured in the ASP.NET Core
// authentication options shouldn't be used, a specific scheme can be specified here.
var result = await HttpContext.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
if (result is not { Succeeded: true })
{
// Only allow local return URLs to prevent open redirect attacks.
return Redirect(Url.IsLocalUrl(returnUrl) ? returnUrl : "/");
}

// Remove the local authentication cookie before triggering a redirection to the remote server.
//
// For scenarios where the default sign-out handler configured in the ASP.NET Core
// authentication options shouldn't be used, a specific scheme can be specified here.
await HttpContext.SignOutAsync();

var properties = new AuthenticationProperties(new Dictionary<string, string>
{
// While not required, the specification encourages sending an id_token_hint
// parameter containing an identity token returned by the server for this user.
[OpenIddictClientAspNetCoreConstants.Properties.IdentityTokenHint] = result.Properties.GetTokenValue(OpenIddictClientAspNetCoreConstants.Tokens.BackchannelIdentityToken)
})
{
// Only allow local return URLs to prevent open redirect attacks.
RedirectUri = Url.IsLocalUrl(returnUrl) ? returnUrl : "/"
};

// Ask the OpenIddict client middleware to redirect the user agent to the identity provider.
return SignOut(properties, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@

Please find out all comments with 'ATTENTION!' because that is required some decisions from you.

# About
# About template

| Name | Description |
| ------------ | ------------------------------------------ |
| Name | Microservice Template for ASP.NET Core API |
| Author | Calabonga SOFT © 2005-2024 Calabonga SOFT |
| Created Date | 2024-11-26 |
| Create From | Microservice-Template NET8.0 |
| Create From | Microservice-Template NET 8.0 |

# Versions

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<!-- The package metadata. Fill in the properties marked as TODO below -->
<!-- Follow the instructions on https://learn.microsoft.com/en-us/nuget/create-packages/package-authoring-best-practices -->
<PackageId>Calabonga.Microservice.Module.Template</PackageId>
<PackageVersion>9.0.0</PackageVersion>
<PackageVersion>9.0.1</PackageVersion>
<Title>Microservice template</Title>
<Authors>Calabonga</Authors>
<Copyright>Calabonga SOFT © 2019 - $([System.DateTime]::Now.ToString(yyyy))</Copyright>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="9.0.0" />
<PackageReference Include="OpenIddict.AspNetCore" Version="5.8.0" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.3" />
<PackageReference Include="Serilog.AspNetCore" Version="9.0.0" />
<PackageReference Include="Serilog.Formatting.Compact" Version="3.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="7.1.0" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="7.2.0" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public class OpenApiDefinition : AppDefinition
// Otherwise, you can change versions of your API by manually.
// If you are not going to use git-versioning, do not forget install package "GitInfo"
// private const string AppVersion = $"{ThisAssembly.Git.SemVer.Major}.{ThisAssembly.Git.SemVer.Minor}.{ThisAssembly.Git.SemVer.Patch}";
public const string AppVersion = "9.0.0";
public const string AppVersion = "9.0.1";

private const string _openApiConfig = "/openapi/v1.json";

Expand Down Expand Up @@ -58,6 +58,7 @@ public override void ConfigureApplication(WebApplication app)
settings.OAuthClientSecret("client-secret-code");
settings.DisplayRequestDuration();
settings.OAuthAppName(AppData.ServiceName);
settings.OAuthUsePkce();
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,13 @@

Please find out all comments with 'ATTENTION!' because that is required some decisions from you.

# About

# About template
| Name | Description |
| ------------ | ------------------------------------------ |
| Name | Microservice Template for ASP.NET Core API |
| Author | Calabonga SOFT © 2005-2024 Calabonga SOFT |
| Created Date | 2024-11-26 |
| Create From | Microservice-Template NET8.0 |
| Create From | Microservice-Template NET 8.0 |

# Versions

Expand Down
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,13 @@ To install templates (`Visual Studio`, `Rider`, `dotnet CLI`) please, read [wiki

## История Nimble Framework

### 2024-12-13 Версия 9.0.1

* Подключен `EnableLogoutEndpointPassthrough` endpoint, а также `SetIntrospectionEndpointUris`.
* Подключена поддержка `PKCE` для `Authorization Code Flow`.
* Обновились nuget-пакеты в проекте `IdentityModule`.
* Обновились nuget-пакеты в проекте `Module`.

### 2024-11-26 Версия 9.0.0

* Обновилась версия платформы NET9.0, установлены nuget-пакеты, соответствующие версии.
Expand Down

0 comments on commit f582730

Please sign in to comment.