Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
daaa43d
Add new api to gather all wwwAuthenticateParameters
Jun 30, 2022
7108c00
refactor
Jun 30, 2022
4ef405b
Request uri fix
Jul 15, 2022
51f71f1
Add additional tests.
Jul 20, 2022
ff29f70
Rename scheme to authScheme
Jul 20, 2022
e790052
Refactoring api
Aug 2, 2022
bd59b3d
Refactoring.
Aug 3, 2022
cab97ae
Refactoring to use Dictionary return type
Aug 5, 2022
6677c1f
Merge remote-tracking branch 'origin/main' into trwalke/wwwAuthentica…
Sep 26, 2022
37d9c43
Adding Authentication header parser and support for authentication info
Sep 27, 2022
bae9643
Refactoring
Sep 27, 2022
af2f19e
Merge remote-tracking branch 'origin/main' into trwalke/wwwAuthentica…
Sep 30, 2022
eb8032f
Apply suggestions from code review
trwalke Oct 13, 2022
8949f55
Addressing PR Feedback.
Oct 18, 2022
8c46a01
Refactoring, more tests
Oct 18, 2022
e87abff
Build fix
Oct 18, 2022
4f4cc68
Adding additional tests
Oct 19, 2022
264921f
Adding NTLM support
Oct 20, 2022
8fbd0e4
Apply suggestions from code review
trwalke Nov 1, 2022
6a58dac
Update src/client/Microsoft.Identity.Client/WwwAuthenticateParameters.cs
trwalke Nov 1, 2022
9b31775
Update src/client/Microsoft.Identity.Client/WwwAuthenticateParameters.cs
trwalke Nov 1, 2022
b068acc
Recfactoring
Nov 2, 2022
384cd11
Merge remote-tracking branch 'origin/main' into trwalke/wwwAuthentica…
Nov 2, 2022
4b56fb2
resolving build errors
Nov 2, 2022
ddbadf8
resolving tests
Nov 2, 2022
0867daa
Updating parameter parsing
Nov 16, 2022
b55f3c2
Updating parsing logic
Nov 30, 2022
1a08dda
Clean up
Nov 30, 2022
fd6733a
Pr Feedback
Dec 1, 2022
9626ec3
test update
Dec 1, 2022
a1cdedf
Update src/client/Microsoft.Identity.Client/WwwAuthenticateParameters.cs
trwalke Dec 1, 2022
37b1ab7
Adding additional tests
Dec 7, 2022
d6a1e1b
Refactoring tests.
Dec 13, 2022
1e9ce55
Merge remote-tracking branch 'origin/pmaytak/net6-only' into trwalke/…
Dec 13, 2022
c3addbe
Refactoring
Dec 13, 2022
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
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,9 @@ internal static class Constants
public static readonly TimeSpan AccessTokenExpirationBuffer = TimeSpan.FromMinutes(5);
public const string EnableSpaAuthCode = "1";
public const string PoPTokenType = "pop";
public const string PoPAuthHeaderPrefix = "PoP";
public const string PoPAuthHeaderPrefix = "PoP";
public const string RequestConfirmation = "req_cnf";
public const string BearerAuthHeaderPrefix = "Bearer";

public static string FormatEnterpriseRegistrationOnPremiseUri(string domain)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Identity.Client.Internal;
using Microsoft.Identity.Client.PlatformsCommon.Factories;
using Microsoft.Identity.Client.Utils;

Expand All @@ -21,6 +22,14 @@ namespace Microsoft.Identity.Client
/// </summary>
public class WwwAuthenticateParameters
{
private static readonly ISet<string> s_knownAuthenticationSchemes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

static WwwAuthenticateParameters()
Comment thread
trwalke marked this conversation as resolved.
Outdated
{
s_knownAuthenticationSchemes.Add(Constants.BearerAuthHeaderPrefix);
s_knownAuthenticationSchemes.Add(Constants.PoPAuthHeaderPrefix);
}

/// <summary>
/// Resource for which to request scopes.
/// This is the App ID URI of the API that returned the WWW-Authenticate header.
Expand Down Expand Up @@ -50,6 +59,16 @@ public class WwwAuthenticateParameters
/// </summary>
public string Error { get; set; }

/// <summary>
/// Scheme.
Comment thread
trwalke marked this conversation as resolved.
Outdated
/// </summary>
public string Scheme { get; set; }
Comment thread
trwalke marked this conversation as resolved.
Outdated

/// <summary>
/// Server Nonce.
Comment thread
trwalke marked this conversation as resolved.
Outdated
/// </summary>
public string ServerNonce { get; set; }
Comment thread
trwalke marked this conversation as resolved.
Outdated

/// <summary>
/// Return the <see cref="RawParameters"/> of key <paramref name="key"/>.
Comment thread
trwalke marked this conversation as resolved.
/// </summary>
Expand Down Expand Up @@ -89,16 +108,47 @@ public string GetTenantId() => Instance.Authority
public static WwwAuthenticateParameters CreateFromResponseHeaders(
HttpResponseHeaders httpResponseHeaders,
string scheme = "Bearer")
{
if (scheme == Constants.BearerAuthHeaderPrefix)
{
return ParseBearerParameters(httpResponseHeaders);
}

if (scheme == Constants.PoPAuthHeaderPrefix)
{
return ParsePopParameters(httpResponseHeaders);
}

return CreateWwwAuthenticateParameters(new Dictionary<string, string>());
}

private static WwwAuthenticateParameters ParseBearerParameters(HttpResponseHeaders httpResponseHeaders)
{
if (httpResponseHeaders.WwwAuthenticate.Any())
{
// TODO: add POP support
AuthenticationHeaderValue bearer = httpResponseHeaders.WwwAuthenticate.First(v => string.Equals(v.Scheme, scheme, StringComparison.OrdinalIgnoreCase));
AuthenticationHeaderValue bearer = httpResponseHeaders.WwwAuthenticate.First(v => string.Equals(v.Scheme, Constants.BearerAuthHeaderPrefix, StringComparison.OrdinalIgnoreCase));
Comment thread
trwalke marked this conversation as resolved.
Outdated
Comment thread
trwalke marked this conversation as resolved.
Outdated
Comment thread
trwalke marked this conversation as resolved.
Outdated
string wwwAuthenticateValue = bearer.Parameter;
return CreateFromWwwAuthenticateHeaderValue(wwwAuthenticateValue);
var parameters = CreateFromWwwAuthenticateHeaderValue(wwwAuthenticateValue);
parameters.Scheme = Constants.BearerAuthHeaderPrefix;
return parameters;
}

return CreateWwwAuthenticateParameters(new Dictionary<string, string>());
return null;
}

private static WwwAuthenticateParameters ParsePopParameters(HttpResponseHeaders httpResponseHeaders)
{
if (httpResponseHeaders.WwwAuthenticate != null)
Comment thread
trwalke marked this conversation as resolved.
Outdated
{
string wwwAuthenticateValue = httpResponseHeaders.WwwAuthenticate.ToString();
var parameters = CreateFromWwwAuthenticateHeaderValue(wwwAuthenticateValue);

parameters.Scheme = Constants.PoPAuthHeaderPrefix;

return parameters;
}

return null;
}

/// <summary>
Expand Down Expand Up @@ -130,17 +180,41 @@ public static Task<WwwAuthenticateParameters> CreateFromResourceResponseAsync(st
return CreateFromResourceResponseAsync(resourceUri, default);
}

/// <summary>
/// Create a list of the known authenticate parameters by attempting to call the resource unauthenticated, and analyzing the response.
/// </summary>
/// <param name="resourceUri">URI of the resource.</param>
/// <param name="cancellationToken">The cancellation token to cancel operation.</param>
/// <returns>a list of WWW-Authenticate Parameters extracted from a response to the unauthenticated call.</returns>
public static async Task<IEnumerable<WwwAuthenticateParameters>> CreateKnownParametersFromResourceResponseAsync(string resourceUri, CancellationToken cancellationToken = default)
Comment thread
trwalke marked this conversation as resolved.
Outdated
Comment thread
trwalke marked this conversation as resolved.
Outdated
{
List<WwwAuthenticateParameters> parameterList = new List<WwwAuthenticateParameters>();

foreach (string scheme in s_knownAuthenticationSchemes)
{
var parameter = await CreateFromResourceResponseAsync(resourceUri, cancellationToken, scheme).ConfigureAwait(false);

if (parameter != null && string.IsNullOrEmpty(parameter.Scheme))
{
parameterList.Add(parameter);
}
}

return parameterList;
}

/// <summary>
/// Create the authenticate parameters by attempting to call the resource unauthenticated, and analyzing the response.
/// </summary>
/// <param name="resourceUri">URI of the resource.</param>
/// <param name="cancellationToken">The cancellation token to cancel operation.</param>
/// <param name="scheme">Authentication scheme. Default is Bearer.</param>
/// <returns>WWW-Authenticate Parameters extracted from response to the unauthenticated call.</returns>
public static Task<WwwAuthenticateParameters> CreateFromResourceResponseAsync(string resourceUri, CancellationToken cancellationToken = default)
public static Task<WwwAuthenticateParameters> CreateFromResourceResponseAsync(string resourceUri, CancellationToken cancellationToken = default, string scheme = "Bearer")
{
var httpClientFactory = PlatformProxyFactory.CreatePlatformProxy(null).CreateDefaultHttpClientFactory();
var httpClient = httpClientFactory.GetHttpClient();
return CreateFromResourceResponseAsync(httpClient, resourceUri, cancellationToken);
return CreateFromResourceResponseAsync(httpClient, resourceUri, cancellationToken, scheme);
}

/// <summary>
Expand All @@ -149,8 +223,9 @@ public static Task<WwwAuthenticateParameters> CreateFromResourceResponseAsync(st
/// <param name="httpClient">Instance of <see cref="HttpClient"/> to make the request with.</param>
/// <param name="resourceUri">URI of the resource.</param>
/// <param name="cancellationToken">The cancellation token to cancel operation.</param>
/// <param name="scheme">Authentication scheme. Default is Bearer.</param>
/// <returns>WWW-Authenticate Parameters extracted from response to the unauthenticated call.</returns>
public static async Task<WwwAuthenticateParameters> CreateFromResourceResponseAsync(HttpClient httpClient, string resourceUri, CancellationToken cancellationToken = default)
public static async Task<WwwAuthenticateParameters> CreateFromResourceResponseAsync(HttpClient httpClient, string resourceUri, CancellationToken cancellationToken = default, string scheme = "Bearer")
{
if (httpClient is null)
{
Expand All @@ -163,7 +238,7 @@ public static async Task<WwwAuthenticateParameters> CreateFromResourceResponseAs

// call this endpoint and see what the header says and return that
HttpResponseMessage httpResponseMessage = await httpClient.GetAsync(resourceUri, cancellationToken).ConfigureAwait(false);
var wwwAuthParam = CreateFromResponseHeaders(httpResponseMessage.Headers);
var wwwAuthParam = CreateFromResponseHeaders(httpResponseMessage.Headers, scheme);
return wwwAuthParam;
}

Expand Down Expand Up @@ -231,6 +306,11 @@ internal static WwwAuthenticateParameters CreateWwwAuthenticateParameters(IDicti
wwwAuthenticateParameters.Error = value;
}

if (values.TryGetValue("WWWAuthenticate: PoP nonce", out value))
Comment thread
trwalke marked this conversation as resolved.
Outdated
{
wwwAuthenticateParameters.ServerNonce = value.Replace("\"", string.Empty);
}

return wwwAuthenticateParameters;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Identity.Client;
using Microsoft.Identity.Client.Internal;
using Microsoft.Identity.Test.Common.Core.Mocks;
using Microsoft.VisualStudio.TestTools.UnitTesting;

Expand Down Expand Up @@ -253,6 +254,30 @@ public void ExtractClaimChallengeFromHeader_IncorrectError_ReturnNull()
Assert.IsNull(WwwAuthenticateParameters.GetClaimChallengeFromResponseHeaders(httpResponse.Headers));
}

[TestMethod]
public async Task ExtractNonceFromHeaderAsync()
{
//Arrange & Act
WwwAuthenticateParameters parameters = await WwwAuthenticateParameters.CreateFromResourceResponseAsync(
"https://testingsts.azurewebsites.net/servernonce/expired",
default,
Constants.PoPAuthHeaderPrefix).ConfigureAwait(false);

//Assert
Assert.IsTrue(parameters.Scheme == Constants.PoPAuthHeaderPrefix);
Assert.IsNotNull(parameters.ServerNonce);
}

//[TestMethod]
//public void ExtractAllParametersFromResponse()
//{
// // Arrange
// HttpResponseMessage httpResponse = CreateBearerAndPopHttpResponse();

// // Act & Assert
// Assert.IsNull(WwwAuthenticateParameters.GetClaimChallengeFromResponseHeaders(httpResponse.Headers));
//}

private static HttpResponseMessage CreateClaimsHttpResponse(string claims)
{
HttpResponseMessage httpResponse = new HttpResponseMessage(HttpStatusCode.Unauthorized);
Expand Down Expand Up @@ -292,5 +317,17 @@ private static HttpResponseMessage CreateInvalidTokenHttpErrorResponse(string te
}
};
}

//private static HttpResponseMessage CreateBearerAndPopHttpResponse()
//{
// return new HttpResponseMessage(HttpStatusCode.Unauthorized)
// {
// Headers =
// {
// { WwwAuthenticateHeaderName, $"Bearer realm=\"\", client_id=\"00000003-0000-0000-c000-000000000000\", authorization_uri=\"https://login.microsoftonline.com/common/oauth2/authorize\", error=\"some_error\", claims=\"{DecodedClaimsHeader}\"" },
// { WwwAuthenticateHeaderName, $"WWWAuthenticate: PoP nonce=\"\", someNonce"}
// }
// };
//}
}
}