Skip to content
This repository has been archived by the owner on Jun 30, 2023. It is now read-only.

Fix AuthenticationParamters #1602

Merged
merged 2 commits into from
May 17, 2019
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
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@

namespace Microsoft.IdentityModel.Clients.ActiveDirectory
{
// This is a helper class and its functionality is not tied to ADAL. It uses a vanilla HttpClient

/// <summary>
/// Contains authentication parameters based on unauthorized response from resource server.
/// </summary>
Expand All @@ -53,36 +55,51 @@ public sealed class AuthenticationParameters
/// <summary>
/// Gets or sets the address of the authority to issue token.
/// </summary>
public string Authority { get; set; }
public string Authority { get; }

/// <summary>
/// Gets or sets the identifier of the target resource that is the recipient of the requested token.
/// </summary>
public string Resource { get; set; }
public string Resource { get; }

private static IHttpManager _httpManager;
static AuthenticationParameters()
{
ModuleInitializer.EnsureModuleInitialized();
}

internal AuthenticationParameters(IHttpManager httpManager)
private AuthenticationParameters(string authority, string resource)
{
_httpManager = httpManager;
Authority = authority;
Resource = resource;
}

/// <summary>
/// Creates authentication parameters from address of the resource. This method expects the resource server to return unauthorized response
/// with WWW-Authenticate header containing authentication parameters.
/// Sends a GET request to the url provided with no Authenticate header. If a 401 Unauthorized is received, this helper will parse the WWW-Authenticate header to
/// retrieve the authority and resource.
/// </summary>
/// <param name="resourceUrl">Address of the resource</param>
/// <returns>AuthenticationParameters object containing authentication parameters</returns>
public async Task<AuthenticationParameters> CreateFromResourceUrlAsync(Uri resourceUrl)
/// <remarks>Most protected APIs, including those owned by Microsoft, no longer advertise a resource. Authentication should be done using MSAL, which uses scopes. See https://aka.ms/msal-net-migration-adal-msal </remarks>
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@henrik-me @jmprieur - how about I add these "remarks" to a nice Obsolete message instead? :D

Copy link
Contributor

@henrik-me henrik-me May 17, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense to me... except some might be using it who will not be able to if it's marked as obsolete


In reply to: 284784777 [](ancestors = 284784777)

public static async Task<AuthenticationParameters> CreateFromResourceUrlAsync(Uri resourceUrl)
{
return await CreateFromResourceUrlCommonAsync(resourceUrl).ConfigureAwait(false);
if (resourceUrl == null)
{
throw new ArgumentNullException("resourceUrl");
}

HttpClient httpClient = new HttpClient();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

httpClient [](start = 23, length = 10)

not sure why we would not want to allow passing in a httpclient, allowing re-use and proxy, etc. ...

HttpResponseMessage response = await httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Get, resourceUrl))
.ConfigureAwait(false);


return await CreateFromUnauthorizedResponseAsync(response).ConfigureAwait(false);
}

/// <summary>
/// Creates authentication parameters from the response received from the response received from the resource. This method expects the response to have unauthorized status and
/// WWW-Authenticate header containing authentication parameters.</summary>
/// Looks at the Http response for an WWW-Authenticate header and parses it to retrieve the authority and resource</summary>
/// <param name="responseMessage">Response received from the resource (e.g. via an http call using HttpClient).</param>
/// <returns>AuthenticationParameters object containing authentication parameters</returns>
/// <remarks>Most protected APIs, including those owned by Microsoft, no longer advertise a resource. Authentication should be done using MSAL, which uses scopes. See https://aka.ms/msal-net-migration-adal-msal </remarks>
public static async Task<AuthenticationParameters> CreateFromUnauthorizedResponseAsync(
HttpResponseMessage responseMessage)
{
Expand All @@ -95,6 +112,7 @@ public static async Task<AuthenticationParameters> CreateFromUnauthorizedRespons
/// </summary>
/// <param name="authenticateHeader">Content of header WWW-Authenticate header</param>
/// <returns>AuthenticationParameters object containing authentication parameters</returns>
/// <remarks>Most protected APIs, including those owned by Microsoft, no longer advertise a resource. Authentication should be done using MSAL, which uses scopes. See https://aka.ms/msal-net-migration-adal-msal </remarks>
public static AuthenticationParameters CreateFromResponseAuthenticateHeader(string authenticateHeader)
{
if (string.IsNullOrWhiteSpace(authenticateHeader))
Expand Down Expand Up @@ -133,53 +151,13 @@ public static AuthenticationParameters CreateFromResponseAuthenticateHeader(stri
throw newEx;
}

var authParams = new AuthenticationParameters(_httpManager);
string param;
authenticateHeaderItems.TryGetValue(AuthorityKey, out param);
authParams.Authority = param;
string authority = param;
authenticateHeaderItems.TryGetValue(ResourceKey, out param);
authParams.Resource = param;

return authParams;
}

private async Task<AuthenticationParameters> CreateFromResourceUrlCommonAsync(Uri resourceUrl)
{
if (resourceUrl == null)
{
throw new ArgumentNullException("resourceUrl");
}

AuthenticationParameters authParams;

try
{
await _httpManager.SendGetAsync(
new Uri(resourceUrl.AbsoluteUri),
null,
new RequestContext(
null, new AdalLogger(Guid.Empty)))
.ConfigureAwait(false);

var ex = new AdalException(AdalError.UnauthorizedResponseExpected);
CoreLoggerBase.Default.ErrorPii(ex);
throw ex;
string resource = param;

}
catch (AdalServiceException ex)
{
IHttpWebResponse response = ex.Response;
if (response == null)
{
var serviceEx = new AdalServiceException(AdalErrorMessage.UnauthorizedHttpStatusCodeExpected, ex);
CoreLoggerBase.Default.ErrorPii(serviceEx);
throw serviceEx;
}

authParams = CreateFromUnauthorizedResponseCommon(response);
}

return authParams;
return new AuthenticationParameters(authority, resource);
}

private static AuthenticationParameters CreateFromUnauthorizedResponseCommon(IHttpWebResponse response)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,5 @@ internal interface IServiceBundle
IPlatformProxy PlatformProxy { get; }
IWsTrustWebRequestManager WsTrustWebRequestManager { get; }
InstanceDiscovery InstanceDiscovery { get; }
AuthenticationParameters AuthenticationParameters { get; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ internal ServiceBundle(
WsTrustWebRequestManager = wsTrustWebRequestManager ?? new WsTrustWebRequestManager(HttpManager);
PlatformProxy = PlatformProxyFactory.GetPlatformProxy();
InstanceDiscovery = new InstanceDiscovery(HttpManager);
AuthenticationParameters = new AuthenticationParameters(HttpManager);
}

/// <inheritdoc />
Expand All @@ -58,10 +57,6 @@ internal ServiceBundle(
/// <inheritdoc />
public InstanceDiscovery InstanceDiscovery { get; }

/// <inheritdoc />
public AuthenticationParameters AuthenticationParameters { get; }


public static ServiceBundle CreateWithCustomHttpManager(IHttpManager httpManager)
{
return new ServiceBundle(httpManager: httpManager, shouldClearCaches: true);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
//----------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//------------------------------------------------------------------------------


using Microsoft.Identity.Test.LabInfrastructure;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Test.ADAL.NET.Common;

namespace Test.ADAL.Integration.SeleniumTests
{
[TestClass]
public class AuthenticationParamtersTest
{

[TestMethod]
public async Task AuthenticationParametersCanBeDiscovered()
{
string protectedApi = "https://graph.microsoft.com/v1.0/me/";

var ap = await AuthenticationParameters.CreateFromResourceUrlAsync(
new Uri(protectedApi))
.ConfigureAwait(false);

// Authority might change, but should be a rare occurence
Assert.AreEqual(ap.Authority, "https://login.microsoftonline.com/common/oauth2/authorize");

// Graph does not provide a resource_id in the response header, probably because they want MSAL to access it
// I couldn't find protected APIs that advertise resources (tried Grasph, AAD Graph, Dynamics...)
Assert.IsNull(ap.Resource);
}


}
}
28 changes: 12 additions & 16 deletions tests/Test.ADAL.NET.Unit.net45/UnitTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,32 +25,28 @@
//
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Net.Http;
using System.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Identity.Core;
using Microsoft.Identity.Core.Cache;
using Microsoft.Identity.Core.OAuth2;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal;
using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.ClientCreds;
using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Helpers;
using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Http;
using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Instance;
using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.OAuth2;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Test.ADAL.Common;
using Microsoft.Identity.Core;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using Test.ADAL.NET.Common;
using Test.ADAL.NET.Common.Mocks;
using Test.Microsoft.Identity.Core.Unit;
using AuthorityType=Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Instance.AuthorityType;
using Microsoft.Identity.Core.OAuth2;
using Microsoft.Identity.Core.Http;
using AuthorityType = Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Instance.AuthorityType;

namespace Test.ADAL.NET.Unit
{
Expand All @@ -68,7 +64,7 @@ public class UnitTests
public void Initialize()
{
ModuleInitializer.ForceModuleInitializationTestOnly();
}
}

[TestMethod]
[Description("Positive Test for UrlEncoding")]
Expand Down