Skip to content

Commit afc2093

Browse files
gautamdshethGautam Sheth
andauthored
Fix #3717 - Added support for custom environment in App registration (#3763)
Co-authored-by: Gautam Sheth <gautam.sheth@staffbase.com>
1 parent fe1bd8b commit afc2093

File tree

4 files changed

+59
-21
lines changed

4 files changed

+59
-21
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/).
4141
- Fixed `Get-PnPPowerPlatformConnector`, `Get-PnPPowerPlatformEnvironment`, `Get-PnPPowerApp`, `Add-PnPFlowOwner`, `Disable-PnPFlow`, `Enable-PnPFlow`, `Export-PnPFlow`, `Get-PnPFlowOwner`, `Get-PnPFlowRun`, `Remove-PnPFlow`, `Remove-PnPFlowOwner` , `Restart-PnPFlow` and `Stop-PnPFlowRun` cmdlets to use the new HTTP endpoints. [#3687](https://github.com/pnp/powershell/pull/3687)
4242
- Fixed `Add-PnPHubSiteAssociation` cmdlet to allow support for multi-geo scenario. [#3568](https://github.com/pnp/powershell/pull/3568)
4343
- Fixed `Enable/Disable-PnPPageScheduling` cmdlet to also work with Viva connections enabled site. [#3713](https://github.com/pnp/powershell/pull/3713)
44+
- Fixed `Register-PnPManagementShellAccess` and `Register-PnPAzureADApp` cmdlets to also work with custom environment.
4445

4546
### Changed
4647

src/Commands/AzureAD/RegisterAzureADApp.cs

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -527,7 +527,14 @@ private X509Certificate2 GetCertificate(PSObject record)
527527
private bool AppExists(string appName, HttpClient httpClient, string token)
528528
{
529529
Host.UI.Write(ConsoleColor.Yellow, Host.UI.RawUI.BackgroundColor, $"Checking if application '{appName}' does not exist yet...");
530-
var azureApps = RestHelper.GetAsync<RestResultCollection<AzureADApp>>(httpClient, $@"https://{PnP.Framework.AuthenticationManager.GetGraphEndPoint(AzureEnvironment)}/v1.0/applications?$filter=displayName eq '{appName}'&$select=Id", token).GetAwaiter().GetResult();
530+
531+
var graphEndpoint = $"https://{AuthenticationManager.GetGraphEndPoint(AzureEnvironment)}";
532+
if (AzureEnvironment == AzureEnvironment.Custom)
533+
{
534+
graphEndpoint = Environment.GetEnvironmentVariable("MicrosoftGraphEndPoint", EnvironmentVariableTarget.Process);
535+
}
536+
537+
var azureApps = RestHelper.GetAsync<RestResultCollection<AzureADApp>>(httpClient, $"{graphEndpoint}/v1.0/applications?$filter=displayName eq '{appName}'&$select=Id", token).GetAwaiter().GetResult();
531538
if (azureApps != null && azureApps.Items.Any())
532539
{
533540
Host.UI.WriteLine();
@@ -571,7 +578,13 @@ private AzureADApp CreateApp(string loginEndPoint, HttpClient httpClient, string
571578
requiredResourceAccess = scopesPayload
572579
};
573580

574-
var azureApp = RestHelper.PostAsync<AzureADApp>(httpClient, $"https://{AuthenticationManager.GetGraphEndPoint(AzureEnvironment)}/v1.0/applications", token, payload).GetAwaiter().GetResult();
581+
var graphEndpoint = $"https://{AuthenticationManager.GetGraphEndPoint(AzureEnvironment)}";
582+
if (AzureEnvironment == AzureEnvironment.Custom)
583+
{
584+
graphEndpoint = Environment.GetEnvironmentVariable("MicrosoftGraphEndPoint", EnvironmentVariableTarget.Process);
585+
}
586+
587+
var azureApp = RestHelper.PostAsync<AzureADApp>(httpClient, $"{graphEndpoint}/v1.0/applications", token, payload).GetAwaiter().GetResult();
575588
if (azureApp != null)
576589
{
577590
Host.UI.WriteLine(ConsoleColor.Yellow, Host.UI.RawUI.BackgroundColor, $"App {azureApp.DisplayName} with id {azureApp.AppId} created.");
@@ -583,7 +596,13 @@ private void StartConsentFlow(string loginEndPoint, AzureADApp azureApp, string
583596
{
584597
//Host.UI.WriteLine(ConsoleColor.Yellow, Host.UI.RawUI.BackgroundColor, $"Starting consent flow.");
585598

586-
var resource = scopes.FirstOrDefault(s => s.resourceAppId == PermissionScopes.ResourceAppId_Graph) != null ? $"https://{AzureAuthHelper.GetGraphEndPoint(AzureEnvironment)}/.default" : "https://microsoft.sharepoint-df.com/.default";
599+
var graphEndpoint = $"https://{AuthenticationManager.GetGraphEndPoint(AzureEnvironment)}";
600+
if (AzureEnvironment == AzureEnvironment.Custom)
601+
{
602+
graphEndpoint = Environment.GetEnvironmentVariable("MicrosoftGraphEndPoint", EnvironmentVariableTarget.Process);
603+
}
604+
605+
var resource = scopes.FirstOrDefault(s => s.resourceAppId == PermissionScopes.ResourceAppId_Graph) != null ? $"{graphEndpoint}/.default" : "https://microsoft.sharepoint-df.com/.default";
587606

588607
var consentUrl = $"{loginEndPoint}/{Tenant}/v2.0/adminconsent?client_id={azureApp.AppId}&scope={resource}&redirect_uri={redirectUri}";
589608

@@ -658,7 +677,13 @@ private void SetLogo(AzureADApp azureApp, string token)
658677
{
659678
WriteVerbose("Setting the logo for the Azure AD app");
660679

661-
var endpoint = $"https://{AuthenticationManager.GetGraphEndPoint(AzureEnvironment)}/v1.0/applications/{azureApp.Id}/logo";
680+
var graphEndpoint = $"https://{AuthenticationManager.GetGraphEndPoint(AzureEnvironment)}";
681+
if (AzureEnvironment == AzureEnvironment.Custom)
682+
{
683+
graphEndpoint = Environment.GetEnvironmentVariable("MicrosoftGraphEndPoint", EnvironmentVariableTarget.Process);
684+
}
685+
686+
var endpoint = $"{graphEndpoint}/v1.0/applications/{azureApp.Id}/logo";
662687

663688
var bytes = File.ReadAllBytes(LogoFilePath);
664689

src/Commands/AzureAD/RegisterManagementShellAccess.cs

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using PnP.Framework;
22
using PnP.PowerShell.Commands.Base;
33
using PnP.PowerShell.Commands.Utilities;
4+
using System;
45
using System.Collections.Generic;
56
using System.Management.Automation;
67
using System.Net.Http;
@@ -50,6 +51,12 @@ protected override void ProcessRecord()
5051
WriteWarning("Please specify the Tenant name for non-commercial clouds, otherwise this operation will fail.");
5152
}
5253

54+
var graphEndpoint = $"https://{AuthenticationManager.GetGraphEndPoint(AzureEnvironment)}";
55+
if (AzureEnvironment == AzureEnvironment.Custom)
56+
{
57+
graphEndpoint = Environment.GetEnvironmentVariable("MicrosoftGraphEndPoint", EnvironmentVariableTarget.Process);
58+
}
59+
5360
Task.Factory.StartNew(() =>
5461
{
5562
if (ParameterSetName == ParameterSet_REGISTER)
@@ -64,7 +71,7 @@ protected override void ProcessRecord()
6471
{
6572
try
6673
{
67-
authManager.GetAccessTokenAsync(new[] { $"https://{GetGraphEndPoint()}/.default" }, source.Token, Microsoft.Identity.Client.Prompt.Consent).GetAwaiter().GetResult();
74+
authManager.GetAccessTokenAsync(new[] { $"{graphEndpoint}/.default" }, source.Token, Microsoft.Identity.Client.Prompt.Consent).GetAwaiter().GetResult();
6875
}
6976
catch (Microsoft.Identity.Client.MsalException)
7077
{
@@ -91,7 +98,7 @@ protected override void ProcessRecord()
9198
var accessToken = string.Empty;
9299
try
93100
{
94-
accessToken = authManager.GetAccessTokenAsync(new[] { $"https://{GetGraphEndPoint()}/.default" }, source.Token).GetAwaiter().GetResult();
101+
accessToken = authManager.GetAccessTokenAsync(new[] { $"{graphEndpoint}/.default" }, source.Token).GetAwaiter().GetResult();
95102
}
96103
catch (Microsoft.Identity.Client.MsalException)
97104
{
@@ -100,7 +107,7 @@ protected override void ProcessRecord()
100107
if (!string.IsNullOrEmpty(accessToken))
101108
{
102109
var httpClient = Framework.Http.PnPHttpClient.Instance.GetHttpClient();
103-
using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, $"https://{GetGraphEndPoint()}/v1.0/organization"))
110+
using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, $"{graphEndpoint}/v1.0/organization"))
104111
{
105112
requestMessage.Version = new System.Version(2, 0);
106113
requestMessage.Headers.Add("Authorization", $"Bearer {accessToken}");
@@ -142,10 +149,5 @@ protected override void StopProcessing()
142149
{
143150
source.Cancel();
144151
}
145-
146-
private string GetGraphEndPoint()
147-
{
148-
return PnP.Framework.AuthenticationManager.GetGraphEndPoint(AzureEnvironment);
149-
}
150152
}
151153
}

src/Commands/Utilities/AzureAuthHelper.cs

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,12 @@ internal static async Task<string> AuthenticateAsync(string tenantId, string use
1919

2020
using (var authManager = PnP.Framework.AuthenticationManager.CreateWithCredentials(username, password, azureEnvironment))
2121
{
22-
return await authManager.GetAccessTokenAsync(new[] { $"https://{GetGraphEndPoint(azureEnvironment)}/.default" });
22+
var graphEndpoint = $"https://{AuthenticationManager.GetGraphEndPoint(azureEnvironment)}";
23+
if (azureEnvironment == AzureEnvironment.Custom)
24+
{
25+
graphEndpoint = Environment.GetEnvironmentVariable("MicrosoftGraphEndPoint", EnvironmentVariableTarget.Process);
26+
}
27+
return await authManager.GetAccessTokenAsync(new[] { $"{graphEndpoint}/.default" });
2328
}
2429
}
2530

@@ -46,7 +51,12 @@ internal static string AuthenticateDeviceLogin(CancellationTokenSource cancellat
4651
authManager.ClearTokenCache();
4752
try
4853
{
49-
return authManager.GetAccessTokenAsync(new string[] { $"https://{GetGraphEndPoint(azureEnvironment)}/.default" }, cancellationTokenSource.Token).GetAwaiter().GetResult();
54+
var graphEndpoint = $"https://{AuthenticationManager.GetGraphEndPoint(azureEnvironment)}";
55+
if (azureEnvironment == AzureEnvironment.Custom)
56+
{
57+
graphEndpoint = Environment.GetEnvironmentVariable("MicrosoftGraphEndPoint", EnvironmentVariableTarget.Process);
58+
}
59+
return authManager.GetAccessTokenAsync(new string[] { $"{graphEndpoint}/.default" }, cancellationTokenSource.Token).GetAwaiter().GetResult();
5060
}
5161
catch (Microsoft.Identity.Client.MsalException)
5262
{
@@ -78,7 +88,12 @@ internal static string AuthenticateInteractive(CancellationTokenSource cancellat
7888
authManager.ClearTokenCache();
7989
try
8090
{
81-
return authManager.GetAccessTokenAsync(new string[] { $"https://{GetGraphEndPoint(azureEnvironment)}/.default" }, cancellationTokenSource.Token).GetAwaiter().GetResult();
91+
var graphEndpoint = $"https://{AuthenticationManager.GetGraphEndPoint(azureEnvironment)}";
92+
if (azureEnvironment == AzureEnvironment.Custom)
93+
{
94+
graphEndpoint = Environment.GetEnvironmentVariable("MicrosoftGraphEndPoint", EnvironmentVariableTarget.Process);
95+
}
96+
return authManager.GetAccessTokenAsync(new string[] { $"{graphEndpoint}/.default" }, cancellationTokenSource.Token).GetAwaiter().GetResult();
8297
}
8398
catch (Microsoft.Identity.Client.MsalException)
8499
{
@@ -91,11 +106,6 @@ internal static string AuthenticateInteractive(CancellationTokenSource cancellat
91106
cancellationTokenSource.Cancel();
92107
}
93108
return null;
94-
}
95-
96-
internal static string GetGraphEndPoint(AzureEnvironment azureEnvironment)
97-
{
98-
return PnP.Framework.AuthenticationManager.GetGraphEndPoint(azureEnvironment);
99-
}
109+
}
100110
}
101111
}

0 commit comments

Comments
 (0)