Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: Improve Get-PnPAuthenticationRealm cmdlet by using HTTP client #2304

Merged
merged 2 commits into from
Sep 3, 2022
Merged
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
46 changes: 19 additions & 27 deletions src/Commands/Base/GetAuthenticationRealm.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System;
using System.Management.Automation;

using System.Net;
using Microsoft.SharePoint.Client;

Expand All @@ -10,7 +9,6 @@ namespace PnP.PowerShell.Commands
[OutputType(typeof(string))]
public class GetAuthenticationRealm : PnPSharePointCmdlet
{

[Parameter(Mandatory = false, Position = 0, ValueFromPipeline = true)]
public string Url;

Expand All @@ -20,38 +18,32 @@ protected override void ProcessRecord()
{
Url = ClientContext.Url;
}
WebRequest request = WebRequest.Create(new Uri(Url) + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");

try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
var bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];

const string bearer = "Bearer realm=\"";
var bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
var client = Framework.Http.PnPHttpClient.Instance.GetHttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "");

var response = client.GetAsync(Url).GetAwaiter().GetResult();

var realmIndex = bearerIndex + bearer.Length;
var bearerResponseHeaderValues = response.Headers.GetValues("WWW-Authenticate");
string bearerResponseHeader = string.Join("", bearerResponseHeaderValues);
const string bearer = "Bearer realm=\"";
var bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);

if (bearerResponseHeader.Length >= realmIndex + 36)
{
var targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
var realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
var targetRealm = bearerResponseHeader.Substring(realmIndex, 36);

Guid realmGuid;
Guid realmGuid;

if (Guid.TryParse(targetRealm, out realmGuid))
{
WriteObject(targetRealm);
}
if (Guid.TryParse(targetRealm, out realmGuid))
{
WriteObject(targetRealm);
}
}
}


}
}