From 48daf862d091e36d2eca8ab2b01038aaf2bbf469 Mon Sep 17 00:00:00 2001 From: Mohammed Ahmed Hussien Date: Fri, 22 Mar 2024 22:37:54 +0300 Subject: [PATCH] Improve the PKCE validation when client call the Authorization Request endpoint and also when the client call the Token Endpoint --- .../Services/AuthorizeResultService.cs | 30 ++++++++++++++----- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/Server/src/OAuth20.Server/Services/AuthorizeResultService.cs b/Server/src/OAuth20.Server/Services/AuthorizeResultService.cs index af8237c..30ade0e 100644 --- a/Server/src/OAuth20.Server/Services/AuthorizeResultService.cs +++ b/Server/src/OAuth20.Server/Services/AuthorizeResultService.cs @@ -81,6 +81,14 @@ public AuthorizeResponse AuthorizeRequest(IHttpContextAccessor httpContextAccess return response; } + if (client.Client.UsePkce && string.IsNullOrWhiteSpace(authorizationRequest.code_challenge)) + { + response.Error = ErrorTypeEnum.InvalidRequest.GetEnumDescription(); + response.ErrorDescription = "code challenge required"; + return response; + + } + // check the return url is match the one that in the client store bool redirectUriIsMatched = client.Client.RedirectUri.Equals(authorizationRequest.redirect_uri, StringComparison.OrdinalIgnoreCase); @@ -300,17 +308,23 @@ private bool codeVerifierIsSendByTheClientThatReceivedTheCode(string codeVerifie if (codeChallengeMethod == Constants.ChallengeMethod.Plain) { - using var shaPalin = SHA256.Create(); - var computedHashPalin = shaPalin.ComputeHash(odeVerifireAsByte); - var tranformedResultPalin = Base64UrlEncoder.Encode(computedHashPalin); - return tranformedResultPalin.Equals(codeChallenge); + return codeVerifier.Equals(codeChallenge); } - using var shaS256 = SHA256.Create(); - var computedHashS256 = shaS256.ComputeHash(odeVerifireAsByte); - var tranformedResultS256 = Base64UrlEncoder.Encode(computedHashS256); + else if (codeChallengeMethod == Constants.ChallengeMethod.SHA256) + { + + using var shaS256 = SHA256.Create(); + var computedHashS256 = shaS256.ComputeHash(odeVerifireAsByte); + var tranformedResultS256 = Base64UrlEncoder.Encode(computedHashS256); + + return tranformedResultS256.Equals(codeChallenge); + } + else + { + return false; + } - return tranformedResultS256.Equals(codeChallenge); }