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

PKCE Feature is now on for AuthServer. #625

Merged
merged 7 commits into from
Sep 18, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 0 additions & 2 deletions .github/workflows/prerelease.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ jobs:
- name: Pack
run: |
dotnet pack -v normal -c Release --include-source -p:PackageVersion=${VERSION} ./Udap.Model/Udap.Model.csproj
dotnet pack -v normal -c Release --include-source -p:PackageVersion=${VERSION} ./Udap.Tefca.Model/Udap.Tefca.Model.csproj
dotnet pack -v normal -c Release --include-source -p:PackageVersion=${VERSION} ./Udap.Util/Udap.Util.csproj
dotnet pack -v normal -c Release --include-source -p:PackageVersion=${VERSION} ./Udap.Common/Udap.Common.csproj
dotnet pack -v normal -c Release --include-source -p:PackageVersion=${VERSION} ./Udap.Metadata.Server/Udap.Metadata.Server.csproj
Expand All @@ -40,7 +39,6 @@ jobs:
- name: Push
run: |
dotnet nuget push ./Udap.Model/bin/Release/*.symbols.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{ secrets.NUGET_API_KEY }}
dotnet nuget push ./Udap.Tefca.Model/bin/Release/*.symbols.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{ secrets.NUGET_API_KEY }}
dotnet nuget push ./Udap.Util/bin/Release/*.symbols.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{ secrets.NUGET_API_KEY }}
dotnet nuget push ./Udap.Common/bin/Release/*.symbols.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{ secrets.NUGET_API_KEY }}
dotnet nuget push ./Udap.Metadata.Server/bin/Release/*.symbols.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{ secrets.NUGET_API_KEY }}
Expand Down
4 changes: 1 addition & 3 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@ jobs:

- name: Pack
run: |
dotnet pack -v normal -c Release --include-source -p:PackageVersion=${VERSION} ./Udap.Model/Udap.Model.csproj
dotnet pack -v normal -c Release --include-source -p:PackageVersion=${VERSION} ./Udap.Tefca.Model/Udap.Tefca.Model.csproj
dotnet pack -v normal -c Release --include-source -p:PackageVersion=${VERSION} ./Udap.Model/Udap.Model.csproj
dotnet pack -v normal -c Release --include-source -p:PackageVersion=${VERSION} ./Udap.Util/Udap.Util.csproj
dotnet pack -v normal -c Release --include-source -p:PackageVersion=${VERSION} ./Udap.Common/Udap.Common.csproj
dotnet pack -v normal -c Release --include-source -p:PackageVersion=${VERSION} ./Udap.Metadata.Server/Udap.Metadata.Server.csproj
Expand All @@ -40,7 +39,6 @@ jobs:
- name: Push
run: |
dotnet nuget push ./Udap.Model/bin/Release/*.symbols.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{ secrets.NUGET_API_KEY }}
dotnet nuget push ./Udap.Tefca.Model/bin/Release/*.symbols.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{ secrets.NUGET_API_KEY }}
dotnet nuget push ./Udap.Util/bin/Release/*.symbols.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{ secrets.NUGET_API_KEY }}
dotnet nuget push ./Udap.Common/bin/Release/*.symbols.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{ secrets.NUGET_API_KEY }}
dotnet nuget push ./Udap.Metadata.Server/bin/Release/*.symbols.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{ secrets.NUGET_API_KEY }}
Expand Down
22 changes: 16 additions & 6 deletions Udap.Client/Client/Extensions/HttpClientTokenRequestExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,11 @@ public static async Task<TokenResponse> ExchangeCodeForTokenResponse(
clone.Parameters.AddOptional(OidcConstants.TokenRequest.RedirectUri, tokenRequest.RedirectUri);
clone.Parameters.AddRequired(UdapConstants.TokenRequest.Udap, UdapConstants.UdapVersionsSupportedValue);

if (!string.IsNullOrEmpty(tokenRequest.CodeVerifier))
{
clone.Parameters.AddRequired(OidcConstants.TokenRequest.CodeVerifier, tokenRequest.CodeVerifier);
}

foreach (var resource in tokenRequest.Resource)
{
clone.Parameters.AddRequired(OidcConstants.TokenRequest.Resource, resource, allowDuplicates: true);
Expand Down Expand Up @@ -108,26 +113,31 @@ internal static async Task<TokenResponse> RequestTokenAsync(this HttpMessageInvo
/// calls this method.
/// </summary>
/// <param name="client">The client.</param>
/// <param name="request">The request.</param>
/// <param name="tokenRequest">The request.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns><see cref="OAuthTokenResponse"/></returns>
public static async Task<OAuthTokenResponse> ExchangeCodeForAuthTokenResponse(
this HttpMessageInvoker client,
AuthorizationCodeTokenRequest request,
AuthorizationCodeTokenRequest tokenRequest,
CancellationToken cancellationToken = default)
{
var clone = request.Clone();
var clone = tokenRequest.Clone();

clone.Parameters.AddRequired(OidcConstants.TokenRequest.GrantType, OidcConstants.GrantTypes.AuthorizationCode);
clone.Parameters.AddRequired(OidcConstants.TokenRequest.Code, request.Code);
clone.Parameters.AddRequired(OidcConstants.TokenRequest.Code, tokenRequest.Code);
// TODO: revisit:: This is not required according to https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.3
// UDAP profiles also do not require it.
// I think that the Duende.IdentityServer.Validation.TokenRequestValidator will always fail without it.
// The https://www.udap.org/UDAPTestTool/ sends the redirect_uri. So not sure on the path forward yet.
clone.Parameters.AddOptional(OidcConstants.TokenRequest.RedirectUri, request.RedirectUri);
clone.Parameters.AddOptional(OidcConstants.TokenRequest.RedirectUri, tokenRequest.RedirectUri);
clone.Parameters.AddRequired(UdapConstants.TokenRequest.Udap, UdapConstants.UdapVersionsSupportedValue);

foreach (var resource in request.Resource)
if (!string.IsNullOrEmpty(tokenRequest.CodeVerifier))
{
clone.Parameters.AddRequired(OidcConstants.TokenRequest.CodeVerifier, tokenRequest.CodeVerifier);
}

foreach (var resource in tokenRequest.Resource)
{
clone.Parameters.AddRequired(OidcConstants.TokenRequest.Resource, resource, allowDuplicates: true);
}
Expand Down
31 changes: 31 additions & 0 deletions Udap.Client/Client/IUdapClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -131,11 +131,42 @@ Task<UdapDynamicClientRegistrationDocument> RegisterClientCredentialsClient(
string? logo = null,
CancellationToken token = default);

Task<HttpResponseMessage> Authorize(
string authorizationUrl,
string clientId,
string? responseType = null,
string? scope = null,
string? redirectUri = null,
string? state = null,
string? nonce = null,
string? loginHint = null,
string? acrValues = null,
string? prompt = null,
string? responseMode = null,
string? codeChallenge = null,
string? codeChallengeMethod = null,
string? display = null,
int? maxAge = null,
string? uiLocales = null,
string? idTokenHint = null,
string? requestUri = null,
object? extra = null);


/// <summary>
/// Generated PKCS and use in the authorization code flow.
/// <seealso cref="https://datatracker.ietf.org/doc/html/rfc7636"/>
/// <seealso cref="https://build.fhir.org/ig/HL7/fhir-udap-security-ig/b2b.html#obtaining-an-authorization-code"/>
/// <seealso cref="https://build.fhir.org/ig/HL7/fhir-udap-security-ig/consumer.html#obtaining-an-authorization-code"/>
/// </summary>
public Pkce GeneratePkce();

Task<TokenResponse> ExchangeCodeForTokenResponse(UdapAuthorizationCodeTokenRequest tokenRequest, CancellationToken token = default);

Task<OAuthTokenResponse> ExchangeCodeForAuthTokenResponse(UdapAuthorizationCodeTokenRequest tokenRequest, CancellationToken token = default);

Task<IEnumerable<SecurityKey>?> ResolveJwtKeys(DiscoveryDocumentRequest? request = null, CancellationToken cancellationToken = default);

Task<DiscoveryDocumentResponse?> ResolveOpenIdConfig(DiscoveryDocumentRequest? request = null, CancellationToken cancellationToken = default);

}
52 changes: 52 additions & 0 deletions Udap.Client/Client/Pkce.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#region (c) 2024 Joseph Shook. All rights reserved.
// /*
// Authors:
// Joseph Shook Joseph.Shook@Surescripts.com
//
// See LICENSE in the project root for license information.
// */
#endregion

using System.Security.Cryptography;
using System.Text;
using Microsoft.IdentityModel.Tokens;

namespace Udap.Client.Client;

public record Pkce
{
/// <summary>
/// PKCE generated and used in the authorization code flow.
/// <seealso cref="https://datatracker.ietf.org/doc/html/rfc7636"/>
/// <seealso cref="https://build.fhir.org/ig/HL7/fhir-udap-security-ig/b2b.html#obtaining-an-authorization-code"/>
/// <seealso cref="https://build.fhir.org/ig/HL7/fhir-udap-security-ig/consumer.html#obtaining-an-authorization-code"/>
/// </summary>
public Pkce()
{
CodeVerifier = GenerateCodeVerifier();
CodeChallenge = GenerateCodeChallenge(CodeVerifier);
}

private string GenerateCodeVerifier()
{
var bytes = new byte[32];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(bytes);
}
return Base64UrlEncoder.Encode(bytes);
}

private string GenerateCodeChallenge(string codeVerifier)
{
using (var sha256 = SHA256.Create())
{
var challengeBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(codeVerifier));
return Base64UrlEncoder.Encode(challengeBytes);
}
}


public string CodeVerifier { get; }
public string CodeChallenge { get; }
}
69 changes: 65 additions & 4 deletions Udap.Client/Client/UdapClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
using Udap.Model.Access;
using Udap.Model.Registration;
using Udap.Model.Statement;
using System.Text;


#if NET7_0_OR_GREATER
using System.Net.Http.Headers;
Expand All @@ -48,6 +50,7 @@ public UdapClient(
UdapClientDiscoveryValidator clientDiscoveryValidator,
IOptionsMonitor<UdapClientOptions> udapClientOptions,
ILogger<UdapClient> logger,
bool enablePkceEnabled = true,
DiscoveryPolicy? discoveryPolicy = null)
{
_httpClient = httpClient;
Expand Down Expand Up @@ -217,6 +220,66 @@ public async Task<UdapDynamicClientRegistrationDocument> RegisterClientCredentia
);
}

public Task<HttpResponseMessage> Authorize(
string authorizationUrl,
string clientId,
string? responseType = null,
string? scope = null,
string? redirectUri = null,
string? state = null,
string? nonce = null,
string? loginHint = null,
string? acrValues = null,
string? prompt = null,
string? responseMode = null,
string? codeChallenge = null,
string? codeChallengeMethod = null,
string? display = null,
int? maxAge = null,
string? uiLocales = null,
string? idTokenHint = null,
string? requestUri = null,
object? extra = null)
{
var url = new RequestUrl(authorizationUrl).CreateAuthorizeUrl(
clientId: clientId,
responseType: responseType,
scope: scope,
redirectUri: redirectUri,
state: state,
nonce: nonce,
loginHint: loginHint,
acrValues: acrValues,
responseMode: responseMode,
codeChallenge: codeChallenge,
codeChallengeMethod: codeChallengeMethod,
display: display,
maxAge: maxAge,
uiLocales: uiLocales,
idTokenHint: idTokenHint,
requestUri: requestUri,
extra: Parameters.FromObject(extra)
);

return _httpClient.GetAsync(url);
}


public bool PkcseEnabled { get; }

/// <summary>
/// UdapClient is enabled for PKCE by default in constructor. This can be overridden by setting this property to false or at construction.
/// Overriding at construction time will avoid the allocation of CodeVerifier and CodeChallenge.
/// <seealso cref="https://datatracker.ietf.org/doc/html/rfc7636"/>
/// <seealso cref="https://build.fhir.org/ig/HL7/fhir-udap-security-ig/b2b.html#obtaining-an-authorization-code">adfaf</seealso> and
/// <seealso cref="https://build.fhir.org/ig/HL7/fhir-udap-security-ig/consumer.html#obtaining-an-authorization-code"/>
/// </summary>
public Pkce GeneratePkce()
{
return new Pkce();
}


/// <summary>
/// Sends a token request using the authorization_code grant type.
/// </summary>
Expand All @@ -228,10 +291,10 @@ public async Task<TokenResponse> ExchangeCodeForTokenResponse(
CancellationToken token = default)
{
var response = await _httpClient.ExchangeCodeForTokenResponse(tokenRequest, token);

_logger.LogDebug("OAuth Client Access Token: {TokenResponse}", JsonSerializer.Serialize(response));
return response;
}

/// <summary>
/// Sends a token request using the authorization_code grant type. Typically used when called
/// from a OAuthHandler implementation. TieredOAuthAuthenticationHandler is an implementation that
Expand Down Expand Up @@ -622,7 +685,5 @@ await response.Content.ReadFromJsonAsync<UdapDynamicClientRegistrationDocument>(

return resultDocument;
}

}

}
2 changes: 1 addition & 1 deletion Udap.Common/Metadata/UdapMetaDataBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@

if (certificate == null)
{
_logger.LogWarning($"Missing default community certificate: {System.Net.WebUtility.UrlEncode(community)}");
_logger.LogWarning($"Missing default community certificate: {System.Web.HttpUtility.UrlEncode(community)}");
Dismissed Show dismissed Hide dismissed
return null;
}

Expand Down
5 changes: 5 additions & 0 deletions Udap.Server/Configuration/ServerSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,11 @@ public class ServerSettings

public bool RequireConsent { get; set; } = true;
public bool AllowRememberConsent { get; set; } = false;

/// <summary>
/// Force UDAP clients to register with
/// </summary>
public bool RequirePkce { get; set; }
}


Expand Down
12 changes: 11 additions & 1 deletion Udap.Server/Mappers/AuthTokenResponseMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,16 @@ public class AuthTokenResponseMapperProfile : Profile
public AuthTokenResponseMapperProfile()
{
CreateMap<OAuthTokenResponse, Microsoft.AspNetCore.Authentication.OAuth.OAuthTokenResponse>()
.ReverseMap();
.ConstructUsing((src, context) =>
{
if (src.Error != null)
{
return Microsoft.AspNetCore.Authentication.OAuth.OAuthTokenResponse.Failed(src.Error);
}
else
{
return Microsoft.AspNetCore.Authentication.OAuth.OAuthTokenResponse.Success(src.Response);
}
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Udap.Model.Registration;
using Udap.Server.Configuration;
using Udap.Server.Storage.Stores;

namespace Udap.Server.Registration;
Expand All @@ -26,15 +27,18 @@ public class UdapDynamicClientRegistrationEndpoint
{
private readonly IUdapDynamicClientRegistrationValidator _validator;
private readonly IUdapClientRegistrationStore _store;
private readonly ServerSettings _serverSettings;
private readonly ILogger<UdapDynamicClientRegistrationEndpoint> _logger;

public UdapDynamicClientRegistrationEndpoint(
IUdapDynamicClientRegistrationValidator validator,
IUdapClientRegistrationStore store,
ServerSettings serverSettings,
ILogger<UdapDynamicClientRegistrationEndpoint> logger)
{
_validator = validator;
_store = store;
_serverSettings = serverSettings;
_logger = logger;
}

Expand Down Expand Up @@ -155,6 +159,10 @@ await context.Response.WriteAsJsonAsync(new UdapDynamicClientRegistrationErrorRe
}
else
{
if (_serverSettings.RequirePkce)
{
result.Client.RequirePkce = true;
}
var upsertFlag = await _store.UpsertClient(result.Client, token);

if (upsertFlag)
Expand Down
18 changes: 0 additions & 18 deletions Udap.Tefca.Model/TefcaConstants.cs

This file was deleted.

Loading
Loading