This repository has been archived by the owner on Jun 30, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 214
Fix AuthenticationParamters #1602
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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> | ||
|
@@ -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> | ||
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(); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
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) | ||
{ | ||
|
@@ -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)) | ||
|
@@ -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) | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
62 changes: 62 additions & 0 deletions
62
tests/Test.ADAL.Integration.net45/HeadlessTetss/AuthenticationParamtersTest.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
|
||
|
||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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)