/// <summary> /// Gets an aptly configured client. /// </summary> /// <param name="account">The account information to be used when generating the client.</param> /// <param name="environment">The environment where the client is connecting.</param> /// <param name="redirectUri">The redirect URI for the client.</param> /// <returns>An aptly configured client.</returns> public IClientApplicationBase GetClient(PartnerAccount account, PartnerEnvironment environment, string redirectUri = null) { IClientApplicationBase app; if (account.IsPropertySet(PartnerAccountPropertyType.CertificateThumbprint) || account.IsPropertySet(PartnerAccountPropertyType.ServicePrincipalSecret)) { app = CreateConfidentialClient( GetAzureCloudInstance(environment), account.GetProperty(PartnerAccountPropertyType.ApplicationId), account.GetProperty(PartnerAccountPropertyType.ServicePrincipalSecret), GetCertificate(account.GetProperty(PartnerAccountPropertyType.CertificateThumbprint)), redirectUri, account.Tenant); } else { app = CreatePublicClient( GetAzureCloudInstance(environment), account.GetProperty(PartnerAccountPropertyType.ApplicationId), redirectUri, account.Tenant); } return(app); }
/// <summary> /// /// </summary> /// <param name="account"></param> /// <param name="environment"></param> /// <param name="redirectUri"></param> /// <returns></returns> public IClientApplicationBase GetClient(PartnerAccount account, PartnerEnvironment environment, string redirectUri = null) { IClientApplicationBase app; if (account.IsPropertySet(PartnerAccountPropertyType.CertificateThumbprint) || account.IsPropertySet(PartnerAccountPropertyType.ServicePrincipalSecret)) { app = SharedTokenCacheClientFactory.CreateConfidentialClient( $"{environment.ActiveDirectoryAuthority}{account.Tenant}", account.GetProperty(PartnerAccountPropertyType.ApplicationId), account.GetProperty(PartnerAccountPropertyType.ServicePrincipalSecret), GetCertificate(account.GetProperty(PartnerAccountPropertyType.CertificateThumbprint)), redirectUri, account.Tenant); } else { app = SharedTokenCacheClientFactory.CreatePublicClient( $"{environment.ActiveDirectoryAuthority}{account.Tenant}", account.GetProperty(PartnerAccountPropertyType.ApplicationId), redirectUri, account.Tenant); } return(app); }
/// <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> /// Initializes a new instance of the <see cref="AuthenticationParameters" /> class. /// </summary> protected AuthenticationParameters(PartnerAccount account, PartnerEnvironment environment, IEnumerable <string> scopes) { account.AssertNotNull(nameof(account)); environment.AssertNotNull(nameof(environment)); scopes.AssertNotNull(nameof(scopes)); Account = account; Environment = environment; Scopes = scopes; }
/// <summary> /// Creates a new instance of the object used to interface with Partner Center. /// </summary> /// <param name="debugAction">The action to write debug statements.</param> /// <returns>An instance of the <see cref="PartnerOperations" /> class.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="debugAction" /> is null. /// </exception> public virtual IPartner CreatePartnerOperations(Action <string> debugAction) { debugAction.AssertNotNull(nameof(debugAction)); PartnerEnvironment env = PartnerEnvironment.PublicEnvironments[PartnerSession.Instance.Context.Environment]; PartnerService.Instance.ApiRootUrl = new Uri(env.PartnerCenterEndpoint); return(PartnerService.Instance.CreatePartnerOperations( new PowerShellCredentials( PartnerSession.Instance.AuthenticationFactory.Authenticate(PartnerSession.Instance.Context, debugAction)), HttpClient)); }
/// <summary> /// Acquires the security token from the authority. /// </summary> /// <returns>The result from the authentication request.</returns> public AuthenticationResult Authenticate(PartnerAccount account, PartnerEnvironment environment, IEnumerable <string> scopes, string message, Action <string> promptAction = null, CancellationToken cancellationToken = default) { return(new AuthenticationResult( "STUB_TOKEN", true, "uniquedId", DateTimeOffset.UtcNow.AddHours(1), DateTimeOffset.UtcNow.AddHours(1), "xxxx-xxxx-xxxx-xxxx", null, "STUB_TOKEN", scopes)); }
public AuthenticationResult Authenticate(PartnerAccount account, PartnerEnvironment environment, IEnumerable <string> scopes, string message = null, Action <string> promptAction = null, CancellationToken cancellationToken = default) { AuthenticationResult authResult = null; IAuthenticator processAuthenticator = Builder.Authenticator; int retries = 5; while (retries-- > 0) { try { while (processAuthenticator != null && processAuthenticator.TryAuthenticate(GetAuthenticationParameters(account, environment, scopes, message), out Task <AuthenticationResult> result, promptAction, cancellationToken)) { authResult = result.ConfigureAwait(true).GetAwaiter().GetResult(); if (authResult != null) { if (authResult.Account?.HomeAccountId != null) { account.Identifier = authResult.Account.HomeAccountId.Identifier; account.ObjectId = authResult.Account.HomeAccountId.ObjectId; } if (account.Tenant.Equals("common", StringComparison.InvariantCultureIgnoreCase) && !string.IsNullOrEmpty(authResult.TenantId)) { account.Tenant = authResult.TenantId; } break; } processAuthenticator = processAuthenticator.Next; } } catch (InvalidOperationException) { continue; } break; } return(authResult ?? null); }
/// <summary> /// Gets the Azure cloud instance based an instance of the <see cref="PartnerEnvironment" /> class. /// </summary> /// <param name="environment">The environment information used to be generate the Azure Cloud instance.</param> /// <returns>The Azure cloud instance based an instance of the <see cref="PartnerEnvironment" /> class.</returns> private static AzureCloudInstance GetAzureCloudInstance(PartnerEnvironment environment) { environment.AssertNotNull(nameof(environment)); if (environment.EnvironmentName == EnvironmentName.AzureChinaCloud) { return(AzureCloudInstance.AzureChina); } else if (environment.EnvironmentName == EnvironmentName.AzureGermanCloud) { return(AzureCloudInstance.AzureGermany); } else if (environment.EnvironmentName == EnvironmentName.AzureCloud) { return(AzureCloudInstance.AzurePublic); } else if (environment.EnvironmentName == EnvironmentName.AzureUSGovernment) { return(AzureCloudInstance.AzureUsGovernment); } return(AzureCloudInstance.None); }
/// <summary> /// Initializes a new instance of the <see cref="RefreshTokenParameters" /> class. /// </summary> public RefreshTokenParameters(PartnerAccount account, PartnerEnvironment environment, IEnumerable <string> scopes) : base(account, environment, scopes) { }
/// <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); }
private AuthenticationParameters GetAuthenticationParameters(PartnerAccount account, PartnerEnvironment environment, IEnumerable <string> scopes, string message = null) { if (account.IsPropertySet(PartnerAccountPropertyType.AccessToken)) { return(new AccessTokenParameters(account, environment, scopes)); } else if (account.IsPropertySet("UseAuthCode")) { return(new InteractiveParameters(account, environment, scopes, message)); } else if (account.IsPropertySet(PartnerAccountPropertyType.RefreshToken)) { return(new RefreshTokenParameters(account, environment, scopes)); } else if (account.Type == AccountType.User) { if (!string.IsNullOrEmpty(account.ObjectId)) { return(new SilentParameters(account, environment, scopes)); } else if (account.IsPropertySet("UseDeviceAuth")) { return(new DeviceCodeParameters(account, environment, scopes)); } return(new InteractiveParameters(account, environment, scopes, message)); } else if (account.Type == AccountType.ServicePrincipal || account.Type == AccountType.Certificate) { return(new ServicePrincipalParameters(account, environment, scopes)); } return(null); }
/// <summary> /// Initializes a new instance of the <see cref="ServicePrincipalParameters" /> class. /// </summary> public ServicePrincipalParameters(PartnerAccount account, PartnerEnvironment environment, IEnumerable <string> scopes) : base(account, environment, scopes) { }
/// <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> /// Initializes a new instance of the <see cref="AuthenticationParameters" /> class. /// </summary> protected AuthenticationParameters(PartnerAccount account, PartnerEnvironment environment, IEnumerable <string> scopes) { Account = account; Environment = environment; Scopes = scopes; }
/// <summary> /// Initializes a new instance of the <see cref="InteractiveParameters" /> class. /// </summary> public InteractiveParameters(PartnerAccount account, PartnerEnvironment environment, IEnumerable <string> scopes, string message) : base(account, environment, scopes) { Message = message; }
/// <summary> /// Acquires the security token from the authority. /// </summary> /// <param name="account">The account information to be used when generating the client.</param> /// <param name="environment">The environment where the client is connecting.</param> /// <param name="scopes">Scopes requested to access a protected service.</param> /// <param name="message">The message to be written to the console.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>The result from the authentication request.</returns> public async Task <AuthenticationResult> AuthenticateAsync(PartnerAccount account, PartnerEnvironment environment, IEnumerable <string> scopes, string message = null, CancellationToken cancellationToken = default) { AuthenticationResult authResult = null; IAuthenticator processAuthenticator = Builder.Authenticator; while (processAuthenticator != null && authResult == null) { authResult = await processAuthenticator.TryAuthenticateAsync(GetAuthenticationParameters(account, environment, scopes, message), cancellationToken).ConfigureAwait(false); if (authResult != null) { if (authResult.Account?.HomeAccountId != null) { account.Identifier = authResult.Account.HomeAccountId.Identifier; account.ObjectId = authResult.Account.HomeAccountId.ObjectId; } if (account.Tenant.Equals("organizations", StringComparison.InvariantCultureIgnoreCase) && !string.IsNullOrEmpty(authResult.TenantId)) { account.Tenant = authResult.TenantId; } break; } processAuthenticator = processAuthenticator.NextAuthenticator; } return(authResult); }
/// <summary> /// Initializes a new instance of the <see cref="DeviceCodeParameters" /> class. /// </summary> public DeviceCodeParameters(PartnerAccount account, PartnerEnvironment environment, IEnumerable <string> scopes) : base(account, environment, scopes) { }
public async Task <AuthenticationResult> AuthenticateAsync(PartnerAccount account, PartnerEnvironment environment, IEnumerable <string> scopes, string message = null, CancellationToken cancellationToken = default) { await Task.CompletedTask; return(new AuthenticationResult( "STUB_TOKEN", true, "uniquedId", DateTimeOffset.UtcNow.AddHours(1), DateTimeOffset.UtcNow.AddHours(1), "xxxx-xxxx-xxxx-xxxx", null, "STUB_TOKEN", scopes, Guid.Empty)); }