/// <summary> /// Performs the execution of the command. /// </summary> protected override void ProcessRecord() { string result = "pass"; PartnerAccount account = new PartnerAccount { Tenant = "organizations", Type = AccountType.User }; PartnerEnvironment environment = PartnerEnvironment.PublicEnvironments[Environment]; if (UseDeviceAuthentication.IsPresent) { account.SetProperty("UseDeviceAuth", "true"); } else { account.SetProperty("UseAuthCode", "true"); } account.SetProperty(PartnerAccountPropertyType.ApplicationId, PowerShellApplicationId); Scheduler.RunTask(async() => { AuthenticationResult authResult = await PartnerSession.Instance.AuthenticationFactory.AuthenticateAsync( account, environment, new[] { $"{environment.PartnerCenterEndpoint}/user_impersonation" }, Message, CancellationToken).ConfigureAwait(false); JsonWebToken jwt = new JsonWebToken(authResult.AccessToken); WriteDebug("Checking if the access token contains the MFA claim..."); /* * Obtain the authentication method reference (AMR) claim. This claim contains the methods used * during authenitcation. See https://tools.ietf.org/html/rfc8176 for more information. */ if (jwt.TryGetClaim("amr", out Claim claim)) { if (!claim.Value.Contains("mfa")) { WriteWarning("Unable to determine if the account authenticated using MFA. See https://aka.ms/partnercenterps-psr-warning for more information."); result = "fail"; } } else { WriteWarning("Unable to find the AMR claim, which means the ability to verify the MFA challenge happened will not be possible. See https://aka.ms/partnercenterps-psr-warning for more information."); result = "fail"; } WriteObject(result); }); }
/// <summary> /// Performs the operations associated with the command. /// </summary> protected override void ProcessRecord() { IPartner partnerOperations; OrganizationProfile profile; PartnerAccount account = new PartnerAccount(); PartnerEnvironment environment = PartnerEnvironment.PublicEnvironments[Environment]; PartnerService.Instance.EnforceMfa = (EnforceMFA.IsPresent && EnforceMFA.ToBool()); if (!string.IsNullOrEmpty(CertificateThumbprint)) { account.SetProperty(PartnerAccountPropertyType.CertificateThumbprint, CertificateThumbprint); } if (!string.IsNullOrEmpty(RefreshToken)) { account.SetProperty(PartnerAccountPropertyType.RefreshToken, RefreshToken); } account.SetProperty(PartnerAccountPropertyType.ApplicationId, PowerShellApplicationId); if (ParameterSetName.Equals(AccessTokenParameterSet, StringComparison.InvariantCultureIgnoreCase)) { account.SetProperty(PartnerAccountPropertyType.AccessToken, AccessToken); account.Type = AccountType.AccessToken; } else if (ParameterSetName.Equals(RefreshTokenParameterSet, StringComparison.InvariantCultureIgnoreCase)) { if (Credential != null) { account.ObjectId = Credential.UserName; account.SetProperty(PartnerAccountPropertyType.ApplicationId, Credential.UserName); account.SetProperty(PartnerAccountPropertyType.ServicePrincipalSecret, Credential.Password.ConvertToString()); } } else if (ParameterSetName.Equals(ServicePrincipalCertificateParameterSet, StringComparison.InvariantCultureIgnoreCase)) { account.SetProperty(PartnerAccountPropertyType.ApplicationId, ApplicationId); } else if (ParameterSetName.Equals(ServicePrincipalParameterSet, StringComparison.InvariantCultureIgnoreCase)) { account.ObjectId = Credential.UserName; account.Type = AccountType.ServicePrincipal; account.SetProperty(PartnerAccountPropertyType.ApplicationId, Credential.UserName); account.SetProperty(PartnerAccountPropertyType.ServicePrincipalSecret, Credential.Password.ConvertToString()); } else { account.Type = AccountType.User; } if (UseDeviceAuthentication.IsPresent) { account.SetProperty("UseDeviceAuth", "true"); } account.SetProperty( PartnerAccountPropertyType.Scope, ParameterSetName.Equals(ServicePrincipalParameterSet, StringComparison.InvariantCultureIgnoreCase) ? $"{environment.AzureAdGraphEndpoint}/.default" : $"{environment.PartnerCenterEndpoint}/user_impersonation"); account.Tenant = string.IsNullOrEmpty(Tenant) ? "common" : Tenant; PartnerSession.Instance.AuthenticationFactory.Authenticate( account, environment, new[] { account.GetProperty(PartnerAccountPropertyType.Scope) }, Message); PartnerSession.Instance.Context = new PartnerContext { Account = account, Environment = environment }; try { partnerOperations = PartnerSession.Instance.ClientFactory.CreatePartnerOperations(); profile = partnerOperations.Profiles.OrganizationProfile.GetAsync().GetAwaiter().GetResult(); PartnerSession.Instance.Context.CountryCode = profile.DefaultAddress.Country; PartnerSession.Instance.Context.Locale = profile.Culture; } catch (PartnerException) { /* This error can safely be ignored */ } WriteObject(PartnerSession.Instance.Context); }
/// <summary> /// Performs the execution of the command. /// </summary> protected override void ProcessRecord() { PartnerAccount account = new PartnerAccount(); if (ParameterSetName.Equals(AccessTokenParameterSet, StringComparison.InvariantCultureIgnoreCase)) { account.SetProperty(PartnerAccountPropertyType.AccessToken, AccessToken); account.Type = AccountType.AccessToken; } else if (ParameterSetName.Equals(ServicePrincipalParameterSet, StringComparison.InvariantCultureIgnoreCase)) { account.ObjectId = Credential.UserName; account.SetProperty(PartnerAccountPropertyType.ServicePrincipalSecret, Credential.Password.ConvertToString()); account.Type = AccountType.ServicePrincipal; } else { account.Type = AccountType.User; } if (UseAuthorizationCode.IsPresent) { account.SetProperty("UseAuthCode", "true"); } if (UseDeviceAuthentication.IsPresent) { account.SetProperty("UseDeviceAuth", "true"); } if (!string.IsNullOrEmpty(RefreshToken)) { account.SetProperty(PartnerAccountPropertyType.RefreshToken, RefreshToken); } account.SetProperty(PartnerAccountPropertyType.ApplicationId, ApplicationId); account.Tenant = string.IsNullOrEmpty(Tenant) ? "common" : Tenant; AuthenticationResult authResult = PartnerSession.Instance.AuthenticationFactory.Authenticate( account, PartnerEnvironment.PublicEnvironments[Environment], Scopes, Message); byte[] cacheData = SharedTokenCacheClientFactory.GetTokenCache(ApplicationId).SerializeMsalV3(); IEnumerable <string> knownPropertyNames = new[] { "AccessToken", "RefreshToken", "IdToken", "Account", "AppMetadata" }; JObject root = JObject.Parse(Encoding.UTF8.GetString(cacheData, 0, cacheData.Length)); IDictionary <string, JToken> known = (root as IDictionary <string, JToken>) .Where(kvp => knownPropertyNames.Any(p => string.Equals(kvp.Key, p, StringComparison.OrdinalIgnoreCase))) .ToDictionary(kvp => kvp.Key, kvp => kvp.Value); IDictionary <string, TokenCacheItem> tokens = new Dictionary <string, TokenCacheItem>(); if (known.ContainsKey("RefreshToken")) { foreach (JToken token in root["RefreshToken"].Values()) { if (token is JObject j) { TokenCacheItem item = new TokenCacheItem { ClientId = ExtractExistingOrEmptyString(j, "client_id"), CredentialType = ExtractExistingOrEmptyString(j, "credential_type"), Environment = ExtractExistingOrEmptyString(j, "environment"), HomeAccountId = ExtractExistingOrEmptyString(j, "home_account_id"), RawClientInfo = ExtractExistingOrEmptyString(j, "client_info"), Secret = ExtractExistingOrEmptyString(j, "secret") }; tokens.Add($"{item.HomeAccountId}-{item.Environment}-RefreshToken-{item.ClientId}--", item); } } } string key = GetTokenCacheKey(authResult); AuthResult result = new AuthResult( authResult.AccessToken, authResult.IsExtendedLifeTimeToken, authResult.UniqueId, authResult.ExpiresOn, authResult.ExtendedExpiresOn, authResult.TenantId, authResult.Account, authResult.IdToken, authResult.Scopes); if (tokens.ContainsKey(key)) { result.RefreshToken = tokens[key].Secret; } FlushDebugMessages(); WriteObject(result); }
/// <summary> /// Executes the operations associated with the cmdlet. /// </summary> public override void ExecuteCmdlet() { Scheduler.RunTask(async() => { IPartner partnerOperations; OrganizationProfile profile; PartnerAccount account = new PartnerAccount(); PartnerEnvironment environment = PartnerEnvironment.PublicEnvironments[Environment]; if (!string.IsNullOrEmpty(CertificateThumbprint)) { account.SetProperty(PartnerAccountPropertyType.CertificateThumbprint, CertificateThumbprint); } if (!string.IsNullOrEmpty(RefreshToken)) { account.SetProperty(PartnerAccountPropertyType.RefreshToken, RefreshToken); } account.SetProperty(PartnerAccountPropertyType.ApplicationId, string.IsNullOrEmpty(ApplicationId) ? PowerShellApplicationId : ApplicationId); if (ParameterSetName.Equals(AccessTokenParameterSet, StringComparison.InvariantCultureIgnoreCase)) { account.SetProperty(PartnerAccountPropertyType.AccessToken, AccessToken); account.Type = AccountType.AccessToken; } else if (ParameterSetName.Equals(RefreshTokenParameterSet, StringComparison.InvariantCultureIgnoreCase)) { if (Credential != null) { account.ObjectId = Credential.UserName; account.SetProperty(PartnerAccountPropertyType.ApplicationId, Credential.UserName); account.SetProperty(PartnerAccountPropertyType.ServicePrincipalSecret, Credential.Password.ConvertToString()); } } else if (ParameterSetName.Equals(ServicePrincipalCertificateParameterSet, StringComparison.InvariantCultureIgnoreCase)) { account.SetProperty(PartnerAccountPropertyType.ApplicationId, ApplicationId); account.Type = AccountType.Certificate; } else if (ParameterSetName.Equals(ServicePrincipalParameterSet, StringComparison.InvariantCultureIgnoreCase)) { account.ObjectId = Credential.UserName; account.Type = AccountType.ServicePrincipal; account.SetProperty(PartnerAccountPropertyType.ApplicationId, Credential.UserName); account.SetProperty(PartnerAccountPropertyType.ServicePrincipalSecret, Credential.Password.ConvertToString()); } else { account.Type = AccountType.User; } if (UseDeviceAuthentication.IsPresent) { account.SetProperty("UseDeviceAuth", "true"); } account.SetProperty( PartnerAccountPropertyType.Scope, ParameterSetName.Equals(ServicePrincipalParameterSet, StringComparison.InvariantCultureIgnoreCase) ? $"{environment.AzureAdGraphEndpoint}/.default" : $"{environment.PartnerCenterEndpoint}/user_impersonation"); account.Tenant = string.IsNullOrEmpty(Tenant) ? "organizations" : Tenant; await PartnerSession.Instance.AuthenticationFactory.AuthenticateAsync( account, environment, new[] { account.GetProperty(PartnerAccountPropertyType.Scope) }, Message, CancellationToken).ConfigureAwait(false); PartnerSession.Instance.Context = new PartnerContext { Account = account, Environment = environment }; try { partnerOperations = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId).ConfigureAwait(false); profile = await partnerOperations.Profiles.OrganizationProfile.GetAsync().ConfigureAwait(false); PartnerSession.Instance.Context.CountryCode = profile.DefaultAddress.Country; PartnerSession.Instance.Context.Locale = profile.Culture; } catch (PartnerException) { /* This error can safely be ignored */ } WriteObject(PartnerSession.Instance.Context); }); }
/// <summary> /// Executes the operations associated with the cmdlet. /// </summary> public override void ExecuteCmdlet() { Scheduler.RunTask(async() => { PartnerAccount account = new PartnerAccount(); string applicationId; if (ParameterSetName.Equals(AccessTokenParameterSet, StringComparison.InvariantCultureIgnoreCase)) { account.SetProperty(PartnerAccountPropertyType.AccessToken, AccessToken); account.Type = AccountType.AccessToken; applicationId = ApplicationId; } else if (ParameterSetName.Equals(ByModuleParameterSet, StringComparison.InvariantCultureIgnoreCase)) { account.SetProperty(PartnerAccountPropertyType.UseDeviceAuth, "true"); account.Type = AccountType.User; applicationId = PowerShellModule.KnownModules[Module].ApplicationId; Scopes = PowerShellModule.KnownModules[Module].Scopes.ToArray(); } else if (ParameterSetName.Equals(ServicePrincipalParameterSet, StringComparison.InvariantCultureIgnoreCase)) { account.ObjectId = Credential.UserName; account.SetProperty(PartnerAccountPropertyType.ServicePrincipalSecret, Credential.Password.ConvertToString()); account.Type = AccountType.ServicePrincipal; applicationId = ApplicationId; } else { account.Type = AccountType.User; applicationId = ApplicationId; } if (!ParameterSetName.Equals(ByModuleParameterSet, StringComparison.InvariantCultureIgnoreCase)) { if (UseAuthorizationCode.IsPresent) { account.SetProperty(PartnerAccountPropertyType.UseAuthCode, "true"); } if (UseDeviceAuthentication.IsPresent) { account.SetProperty(PartnerAccountPropertyType.UseDeviceAuth, "true"); } } if (!string.IsNullOrEmpty(RefreshToken)) { account.SetProperty(PartnerAccountPropertyType.RefreshToken, RefreshToken); } account.SetProperty(PartnerAccountPropertyType.ApplicationId, applicationId); account.Tenant = string.IsNullOrEmpty(Tenant) ? "organizations" : Tenant; AuthenticationResult authResult = await PartnerSession.Instance.AuthenticationFactory.AuthenticateAsync( account, PartnerEnvironment.PublicEnvironments[Environment], Scopes, Message, CancellationToken).ConfigureAwait(false); byte[] cacheData = SharedTokenCacheClientFactory.GetMsalCacheStorage(ApplicationId).ReadData(); IEnumerable <string> knownPropertyNames = new[] { "AccessToken", "RefreshToken", "IdToken", "Account", "AppMetadata" }; JObject root = JObject.Parse(Encoding.UTF8.GetString(cacheData, 0, cacheData.Length)); IDictionary <string, JToken> known = (root as IDictionary <string, JToken>) .Where(kvp => knownPropertyNames.Any(p => string.Equals(kvp.Key, p, StringComparison.OrdinalIgnoreCase))) .ToDictionary(kvp => kvp.Key, kvp => kvp.Value); IDictionary <string, TokenCacheItem> tokens = new Dictionary <string, TokenCacheItem>(); if (known.ContainsKey("RefreshToken")) { foreach (JToken token in root["RefreshToken"].Values()) { if (token is JObject j) { TokenCacheItem item = new TokenCacheItem { ClientId = ExtractExistingOrEmptyString(j, "client_id"), CredentialType = ExtractExistingOrEmptyString(j, "credential_type"), Environment = ExtractExistingOrEmptyString(j, "environment"), HomeAccountId = ExtractExistingOrEmptyString(j, "home_account_id"), RawClientInfo = ExtractExistingOrEmptyString(j, "client_info"), Secret = ExtractExistingOrEmptyString(j, "secret") }; tokens.Add($"{item.HomeAccountId}-{item.Environment}-RefreshToken-{item.ClientId}--", item); } } } AuthResult result = new AuthResult( authResult.AccessToken, authResult.IsExtendedLifeTimeToken, authResult.UniqueId, authResult.ExpiresOn, authResult.ExtendedExpiresOn, authResult.TenantId, authResult.Account, authResult.IdToken, authResult.Scopes, authResult.CorrelationId); if (authResult.Account != null) { string key = SharedTokenCacheClientFactory.GetTokenCacheKey(authResult, applicationId); if (tokens.ContainsKey(key)) { result.RefreshToken = tokens[key].Secret; } } WriteObject(result); }); }