Skip to content

Commit c524ad5

Browse files
committed
Excaped special characters on path segments
1 parent e192b34 commit c524ad5

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

src/Authentication/Authentication/Cmdlets/InvokeMgGraphRequest.cs

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
using System.Text;
2121
using System.Threading;
2222
using System.Threading.Tasks;
23+
using System.Web;
2324
using static Microsoft.Graph.PowerShell.Authentication.Helpers.AsyncHelpers;
2425
using DriveNotFoundException = System.Management.Automation.DriveNotFoundException;
2526

@@ -294,6 +295,7 @@ private async Task ReportResponseStatusASync(HttpMessageFormatter responseMessag
294295
/// <returns></returns>
295296
private HttpRequestMessage GetRequest(HttpClient httpClient, Uri uri)
296297
{
298+
297299
var requestUri = PrepareUri(httpClient, uri);
298300
var httpMethod = GetHttpMethod(Method);
299301
// create the base WebRequest object
@@ -346,7 +348,6 @@ private HttpRequestMessage GetRequest(HttpClient httpClient, Uri uri)
346348
request.Headers.Add(HttpKnownHeaderNames.UserAgent, GraphRequestSession.UserAgent);
347349
}
348350
}
349-
350351
return request;
351352
}
352353

@@ -359,6 +360,7 @@ private HttpRequestMessage GetRequest(HttpClient httpClient, Uri uri)
359360
private Uri PrepareUri(HttpClient httpClient, Uri uri)
360361
{
361362
UriBuilder uriBuilder;
363+
362364
// For AbsoluteUri such as /beta/groups?$count=true, Get the scheme and host from httpClient
363365
// Then use them to compose a new Url with the URL fragment.
364366
if (uri.IsAbsoluteUri)
@@ -401,8 +403,31 @@ private Uri PrepareUri(HttpClient httpClient, Uri uri)
401403
// set body to null to prevent later FillRequestStream
402404
Body = null;
403405
}
406+
return EscapeDataStrings(uriBuilder.Uri);
407+
}
404408

405-
return uriBuilder.Uri;
409+
/// <summary>
410+
/// Escape data string/url encode Uris that have paths containing special characters like #.
411+
/// For a path like /beta/users/first.last_foo.com#EXT#@contoso.onmicrosoft.com, the last segment contains special characters that need to be escaped
412+
/// </summary>
413+
/// <param name="uri"></param>
414+
/// <returns></returns>
415+
private Uri EscapeDataStrings(Uri uri)
416+
{
417+
int counter = 0;
418+
var pathSegments = uri.OriginalString.Split('/');
419+
StringBuilder sb = new StringBuilder();
420+
foreach (var segment in pathSegments)
421+
{
422+
//Skips the left part of the uri i.e https://graph.microsoft.com
423+
if (counter > 2)
424+
{
425+
sb.Append("/" + Uri.EscapeDataString(segment));
426+
}
427+
counter++;
428+
}
429+
Uri escapedUri = new Uri(uri.GetLeftPart(UriPartial.Authority) + sb.ToString());
430+
return escapedUri;
406431
}
407432

408433
private void ThrowIfError(ErrorRecord error)

0 commit comments

Comments
 (0)