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

Fix: reuse existing HTTP client instead of creating a new one #2682

Merged
merged 2 commits into from
Dec 26, 2022
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/).
- Made PropertiesJSON an optional parameter on `Add-PnPVivaConnectionsDashboardACE` as it is not always required when adding an ACE
- Added a 10 second timeout on the new version check on `Connect-PnPOnline` to prevent the cmdlet from hanging when the connection is slow, GitHub being blocked by a firewall or GitHub being unavailable [#2550](https://github.com/pnp/powershell/pull/2550)
- Improved `Add-PnPField`, `Get-PnPListItem` and `Get-PnPSiteDesignRun` cmdlets by improving null checks based on warnings from compiler. [#PR1](https://github.com/pnp/powershell/commit/791b031d5fa844f1e6961b1136df9f79f19bfdcd) and [#PR2](https://github.com/pnp/powershell/commit/d56f3cd497be79170f68b29be490b222bf042aaa)
- Improved `Register-PnPAzureADApp` and `Register-PnPManagementShellAccess` cmdlets to reuse existing HTTP client instead of creating a new one. [#2682](https://github.com/pnp/powershell/pull/2682)
- Improved `Register-PnPAzureADApp` cmdlet based on compiler warnings. [#2682](https://github.com/pnp/powershell/pull/2682)

### Removed

Expand Down
36 changes: 17 additions & 19 deletions src/Commands/AzureAD/RegisterAzureADApp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -195,25 +195,24 @@ protected override void ProcessRecord()
if (!string.IsNullOrEmpty(token))
{
var cert = GetCertificate(record);
var httpClient = Framework.Http.PnPHttpClient.Instance.GetHttpClient();

using (var httpClient = new HttpClient())
if (!AppExists(ApplicationName, httpClient, token))
{
if (!AppExists(ApplicationName, httpClient, token))
{
var azureApp = CreateApp(loginEndPoint, httpClient, token, cert, redirectUri, scopes);

record.Properties.Add(new PSVariableProperty(new PSVariable("AzureAppId/ClientId", azureApp.AppId)));
record.Properties.Add(new PSVariableProperty(new PSVariable("Certificate Thumbprint", cert.GetCertHashString())));
byte[] certPfxData = cert.Export(X509ContentType.Pfx, CertificatePassword);
var base64String = Convert.ToBase64String(certPfxData);
record.Properties.Add(new PSVariableProperty(new PSVariable("Base64Encoded", base64String)));
StartConsentFlow(loginEndPoint, azureApp, redirectUri, token, httpClient, record, messageWriter, scopes);
}
else
{
throw new PSInvalidOperationException($"The application with name {ApplicationName} already exists.");
}
var azureApp = CreateApp(loginEndPoint, httpClient, token, cert, redirectUri, scopes);

record.Properties.Add(new PSVariableProperty(new PSVariable("AzureAppId/ClientId", azureApp.AppId)));
record.Properties.Add(new PSVariableProperty(new PSVariable("Certificate Thumbprint", cert.GetCertHashString())));
byte[] certPfxData = cert.Export(X509ContentType.Pfx, CertificatePassword);
var base64String = Convert.ToBase64String(certPfxData);
record.Properties.Add(new PSVariableProperty(new PSVariable("Base64Encoded", base64String)));
StartConsentFlow(loginEndPoint, azureApp, redirectUri, token, httpClient, record, messageWriter, scopes);
}
else
{
throw new PSInvalidOperationException($"The application with name {ApplicationName} already exists.");
}

}
}

Expand Down Expand Up @@ -452,7 +451,7 @@ private string GetAuthToken(CmdletMessageWriter messageWriter)

private X509Certificate2 GetCertificate(PSObject record)
{
var cert = new X509Certificate2();
X509Certificate2 cert;
if (ParameterSetName == ParameterSet_EXISTINGCERT)
{
if (!Path.IsPathRooted(CertificatePath))
Expand Down Expand Up @@ -519,7 +518,6 @@ private X509Certificate2 GetCertificate(PSObject record)
var pfxPath = string.Empty;
var cerPath = string.Empty;


if (Directory.Exists(OutPath))
{
pfxPath = Path.Combine(OutPath, $"{ApplicationName}.pfx");
Expand Down Expand Up @@ -592,7 +590,7 @@ private AzureADApp CreateApp(string loginEndPoint, HttpClient httpClient, string
}
},
requiredResourceAccess = scopesPayload
};
};

var azureApp = RestHelper.PostAsync<AzureADApp>(httpClient, $"https://{AuthenticationManager.GetGraphEndPoint(AzureEnvironment)}/v1.0/applications", token, payload).GetAwaiter().GetResult();
if (azureApp != null)
Expand Down
30 changes: 13 additions & 17 deletions src/Commands/AzureAD/RegisterManagementShellAccess.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@ protected override void ProcessRecord()
}
catch (Microsoft.Identity.Client.MsalException)
{

}
}
}
Expand Down Expand Up @@ -96,32 +95,29 @@ protected override void ProcessRecord()
}
catch (Microsoft.Identity.Client.MsalException)
{

}

if (!string.IsNullOrEmpty(accessToken))
{
using (var httpClient = new HttpClient())
var httpClient = Framework.Http.PnPHttpClient.Instance.GetHttpClient();
using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, $"https://{GetGraphEndPoint()}/v1.0/organization"))
{
using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, $"https://{GetGraphEndPoint()}/v1.0/organization"))
requestMessage.Headers.Add("Authorization", $"Bearer {accessToken}");
requestMessage.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var response = httpClient.SendAsync(requestMessage).GetAwaiter().GetResult();
if (response.IsSuccessStatusCode)
{
requestMessage.Headers.Add("Authorization", $"Bearer {accessToken}");
requestMessage.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var response = httpClient.SendAsync(requestMessage).GetAwaiter().GetResult();
if (response.IsSuccessStatusCode)
var responseContent = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
var responseJson = JsonSerializer.Deserialize<JsonElement>(responseContent);
if (responseJson.TryGetProperty("value", out JsonElement valueElement))
{
var responseContent = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
var responseJson = JsonSerializer.Deserialize<JsonElement>(responseContent);
if (responseJson.TryGetProperty("value", out JsonElement valueElement))
foreach (var organization in valueElement.EnumerateArray())
{
foreach (var organization in valueElement.EnumerateArray())
if (organization.TryGetProperty("id", out JsonElement idElement))
{
if (organization.TryGetProperty("id", out JsonElement idElement))
{
tenantId = idElement.GetString();
tenantId = idElement.GetString();

break;
}
break;
}
}
}
Expand Down