Пример #1
0
        public override void ExecuteCmdlet()
        {
            CreatePSServicePrincipalParameters createParameters = new CreatePSServicePrincipalParameters
            {
                ApplicationId  = ApplicationId,
                AccountEnabled = !DisableAccount.IsPresent
            };

            WriteObject(ActiveDirectoryClient.CreateServicePrincipal(createParameters));
        }
        protected override void ProcessRecord()
        {
            CreatePSServicePrincipalParameters createParameters = new CreatePSServicePrincipalParameters
            {
                ApplicationId  = ApplicationId,
                AccountEnabled = !DisableAccount.IsPresent
            };

            WriteObject(ActiveDirectoryClient.CreateServicePrincipal(createParameters));
        }
        public PSADServicePrincipal CreateServicePrincipal(CreatePSServicePrincipalParameters createParameters)
        {
            IList <PasswordCredential> passwordCredentials = createParameters.PasswordCredentials != null
                ? createParameters.PasswordCredentials.Select(psCredential => psCredential.ToGraphPasswordCredential()).ToList()
                : null;

            IList <KeyCredential> keyCredentials = createParameters.KeyCredentials != null
                ? createParameters.KeyCredentials.Select(psCredential => psCredential.ToGraphKeyCredential()).ToList()
                : null;

            ServicePrincipalCreateParameters graphParameters = new ServicePrincipalCreateParameters
            {
                AppId               = createParameters.ApplicationId.ToString(),
                AccountEnabled      = createParameters.AccountEnabled,
                KeyCredentials      = keyCredentials,
                PasswordCredentials = passwordCredentials
            };

            try
            {
                return(GraphClient.ServicePrincipals.Create(graphParameters).ToPSADServicePrincipal());
            }
            catch (GraphErrorException ce)
            {
                if (ce.Response.StatusCode == HttpStatusCode.Forbidden)
                {
                    AADObject currentUser = GraphClient.Objects.GetCurrentUser();
                    if (currentUser != null && string.Equals(currentUser.UserType, "Guest", StringComparison.InvariantCultureIgnoreCase))
                    {
                        throw new InvalidOperationException(ProjectResources.CreateServicePrincipalNotAllowedGuestUser);
                    }
                }

                throw;
            }
        }
Пример #4
0
        private void CreateSimpleServicePrincipal()
        {
            var subscriptionId = DefaultProfile.DefaultContext.Subscription.Id;

            if (!this.IsParameterBound(c => c.Scope))
            {
                Scope = string.Format("/subscriptions/{0}", subscriptionId);
                WriteVerbose(string.Format("No scope provided - using the default scope '{0}'", Scope));
            }

            AuthorizationClient.ValidateScope(Scope, true);

            if (!this.IsParameterBound(c => c.Role))
            {
                Role = "Contributor";
                WriteVerbose(string.Format("No role provided - using the default role '{0}'", Role));
            }

            if (!this.IsParameterBound(c => c.StartDate))
            {
                DateTime currentTime = DateTime.UtcNow;
                StartDate = currentTime;
                WriteVerbose("No start date provided - using the current time as default.");
            }

            if (!this.IsParameterBound(c => c.EndDate))
            {
                EndDate = StartDate.AddYears(1);
                WriteVerbose("No end date provided - using the default value of one year after the start date.");
            }

            if (!this.IsParameterBound(c => c.DisplayName))
            {
                DisplayName = "azure-powershell-" + StartDate.ToString("MM-dd-yyyy-HH-mm-ss");
                WriteVerbose(string.Format("No display name provided - using the default display name of '{0}'", DisplayName));
            }

            var identifierUri = "http://" + DisplayName;

            // Handle credentials
            if (!this.IsParameterBound(c => c.Password))
            {
                // If no credentials provided, set the password to a randomly generated GUID
                Password = Guid.NewGuid().ToString().ConvertToSecureString();
            }

            // Create an application and get the applicationId
            var passwordCredential = new PSADPasswordCredential()
            {
                StartDate = StartDate,
                EndDate   = EndDate,
                KeyId     = Guid.NewGuid(),
                Password  = SecureStringExtensions.ConvertToString(Password)
            };

            if (!this.IsParameterBound(c => c.ApplicationId))
            {
                CreatePSApplicationParameters appParameters = new CreatePSApplicationParameters
                {
                    DisplayName         = DisplayName,
                    IdentifierUris      = new[] { identifierUri },
                    HomePage            = identifierUri,
                    PasswordCredentials = new PSADPasswordCredential[]
                    {
                        passwordCredential
                    }
                };

                if (ShouldProcess(target: appParameters.DisplayName, action: string.Format("Adding a new application for with display name '{0}'", appParameters.DisplayName)))
                {
                    var application = ActiveDirectoryClient.CreateApplication(appParameters);
                    ApplicationId = application.ApplicationId;
                    WriteVerbose(string.Format("No application id provided - created new AD application with application id '{0}'", ApplicationId));
                }
            }

            CreatePSServicePrincipalParameters createParameters = new CreatePSServicePrincipalParameters
            {
                ApplicationId       = ApplicationId,
                AccountEnabled      = true,
                PasswordCredentials = new PSADPasswordCredential[]
                {
                    passwordCredential
                }
            };

            if (ShouldProcess(target: createParameters.ApplicationId.ToString(), action: string.Format("Adding a new service principal to be associated with an application having AppId '{0}'", createParameters.ApplicationId)))
            {
                var servicePrincipal = ActiveDirectoryClient.CreateServicePrincipal(createParameters);
                WriteObject(servicePrincipal);
                if (this.IsParameterBound(c => c.SkipAssignment))
                {
                    WriteVerbose("Skipping role assignment for the service principal.");
                    return;
                }

                FilterRoleAssignmentsOptions parameters = new FilterRoleAssignmentsOptions()
                {
                    Scope = this.Scope,
                    RoleDefinitionName = this.Role,
                    ADObjectFilter     = new ADObjectFilterOptions
                    {
                        SPN = servicePrincipal.ApplicationId.ToString(),
                        Id  = servicePrincipal.Id.ToString()
                    },
                    ResourceIdentifier = new ResourceIdentifier()
                    {
                        Subscription = subscriptionId
                    },
                    CanDelegate = false
                };

                for (var i = 0; i < 6; i++)
                {
                    try
                    {
                        TestMockSupport.Delay(5000);
                        PoliciesClient.CreateRoleAssignment(parameters);
                        var ra = PoliciesClient.FilterRoleAssignments(parameters, subscriptionId);
                        if (ra != null)
                        {
                            WriteVerbose(string.Format("Role assignment with role '{0}' and scope '{1}' successfully created for the created service principal.", this.Role, this.Scope));
                            break;
                        }
                    }
                    catch (Exception)
                    {
                        // Do nothing
                    }
                }
            }
        }
Пример #5
0
        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                if (this.ParameterSetName == SimpleParameterSet)
                {
                    CreateSimpleServicePrincipal();
                    return;
                }

                if (this.IsParameterBound(c => c.ApplicationObject))
                {
                    ApplicationId = ApplicationObject.ApplicationId;
                    DisplayName   = ApplicationObject.DisplayName;
                }

                if (ApplicationId == Guid.Empty)
                {
                    string uri = "http://" + DisplayName.Trim().Replace(' ', '_');

                    // Create an application and get the applicationId
                    CreatePSApplicationParameters appParameters = new CreatePSApplicationParameters
                    {
                        DisplayName    = DisplayName,
                        IdentifierUris = new[] { uri },
                        HomePage       = uri
                    };

                    if (ShouldProcess(target: appParameters.DisplayName, action: string.Format("Adding a new application for with display name '{0}'", appParameters.DisplayName)))
                    {
                        var application = ActiveDirectoryClient.CreateApplication(appParameters);
                        ApplicationId   = application.ApplicationId;
                    }
                }

                CreatePSServicePrincipalParameters createParameters = new CreatePSServicePrincipalParameters
                {
                    ApplicationId  = ApplicationId,
                    AccountEnabled = true
                };

                if (this.IsParameterBound(c => c.Password))
                {
                    string decodedPassword = SecureStringExtensions.ConvertToString(Password);
                    createParameters.PasswordCredentials = new PSADPasswordCredential[]
                    {
                        new PSADPasswordCredential
                        {
                            StartDate = StartDate,
                            EndDate   = EndDate,
                            KeyId     = Guid.NewGuid(),
                            Password  = decodedPassword
                        }
                    };
                }
                else if (this.IsParameterBound(c => c.PasswordCredential))
                {
                    createParameters.PasswordCredentials = PasswordCredential;
                }
                else if (this.IsParameterBound(c => c.CertValue))
                {
                    createParameters.KeyCredentials = new PSADKeyCredential[]
                    {
                        new PSADKeyCredential
                        {
                            StartDate = StartDate,
                            EndDate   = EndDate,
                            KeyId     = Guid.NewGuid(),
                            CertValue = CertValue
                        }
                    };
                }
                else if (this.IsParameterBound(c => c.KeyCredential))
                {
                    createParameters.KeyCredentials = KeyCredential;
                }

                if (ShouldProcess(target: createParameters.ApplicationId.ToString(), action: string.Format("Adding a new service principal to be associated with an application having AppId '{0}'", createParameters.ApplicationId)))
                {
                    var servicePrincipal = ActiveDirectoryClient.CreateServicePrincipal(createParameters);
                    WriteObject(servicePrincipal);
                }
            });
        }
Пример #6
0
        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                if (ApplicationId == Guid.Empty)
                {
                    string uri = "http://" + DisplayName.Trim().Replace(' ', '_');

                    // Create an application and get the applicationId
                    CreatePSApplicationParameters appParameters = new CreatePSApplicationParameters
                    {
                        DisplayName    = DisplayName,
                        IdentifierUris = new[] { uri },
                        HomePage       = uri
                    };

                    if (ShouldProcess(target: appParameters.DisplayName, action: string.Format("Adding a new application for with display name '{0}'", appParameters.DisplayName)))
                    {
                        var application = ActiveDirectoryClient.CreateApplication(appParameters);
                        ApplicationId   = application.ApplicationId;
                    }
                }

                CreatePSServicePrincipalParameters createParameters = new CreatePSServicePrincipalParameters
                {
                    ApplicationId  = ApplicationId,
                    AccountEnabled = true
                };

                switch (ParameterSetName)
                {
                case ParameterSet.ApplicationWithPasswordPlain:
                case ParameterSet.DisplayNameWithPasswordPlain:
                    createParameters.PasswordCredentials = new PSADPasswordCredential[]
                    {
                        new PSADPasswordCredential
                        {
                            StartDate = StartDate,
                            EndDate   = EndDate,
                            KeyId     = Guid.NewGuid(),
                            Password  = Password
                        }
                    };
                    break;

                case ParameterSet.ApplicationWithPasswordCredential:
                case ParameterSet.DisplayNameWithPasswordCredential:
                    createParameters.PasswordCredentials = PasswordCredentials;
                    break;

                case ParameterSet.ApplicationWithKeyPlain:
                case ParameterSet.DisplayNameWithKeyPlain:
                    createParameters.KeyCredentials = new PSADKeyCredential[]
                    {
                        new PSADKeyCredential
                        {
                            StartDate = StartDate,
                            EndDate   = EndDate,
                            KeyId     = Guid.NewGuid(),
                            CertValue = CertValue
                        }
                    };
                    break;

                case ParameterSet.ApplicationWithKeyCredential:
                case ParameterSet.DisplayNameWithKeyCredential:
                    createParameters.KeyCredentials = KeyCredentials;
                    break;
                }

                if (ShouldProcess(target: createParameters.ApplicationId.ToString(), action: string.Format("Adding a new service principal to be associated with an application having AppId '{0}'", createParameters.ApplicationId)))
                {
                    WriteObject(ActiveDirectoryClient.CreateServicePrincipal(createParameters));
                }
            });
        }
        private void CreateSimpleServicePrincipal()
        {
            var subscriptionId = DefaultContext.Subscription?.Id;

            if (!this.IsParameterBound(c => c.StartDate))
            {
                DateTime currentTime = DateTime.UtcNow;
                StartDate = currentTime;
                WriteVerbose("No start date provided - using the current time as default.");
            }

            if (!this.IsParameterBound(c => c.EndDate))
            {
                EndDate = StartDate.AddYears(1);
                WriteVerbose(Resources.Properties.Resources.DefaultEndDateUsed);
            }

            if (!this.IsParameterBound(c => c.DisplayName))
            {
                DisplayName = "azure-powershell-" + StartDate.ToString("MM-dd-yyyy-HH-mm-ss");
                WriteVerbose(string.Format("No display name provided - using the default display name of '{0}'", DisplayName));
            }

            var identifierUri = "http://" + DisplayName;

            bool printPassword          = false;
            bool printUseExistingSecret = true;

            // Handle credentials
            var Password = Guid.NewGuid().ToString().ConvertToSecureString();

            // Create an application and get the applicationId
            if (!this.IsParameterBound(c => c.ApplicationId))
            {
                printUseExistingSecret = false;
                CreatePSApplicationParameters appParameters = new CreatePSApplicationParameters
                {
                    DisplayName         = DisplayName,
                    IdentifierUris      = new[] { identifierUri },
                    HomePage            = identifierUri,
                    PasswordCredentials = new PSADPasswordCredential[]
                    {
                        new PSADPasswordCredential()
                        {
                            StartDate = StartDate,
                            EndDate   = EndDate,
                            KeyId     = Guid.NewGuid(),
                            Password  = SecureStringExtensions.ConvertToString(Password)
                        }
                    }
                };

                if (ShouldProcess(target: appParameters.DisplayName, action: string.Format("Adding a new application for with display name '{0}'", appParameters.DisplayName)))
                {
                    var application = ActiveDirectoryClient.CreateApplication(appParameters);
                    ApplicationId = application.ApplicationId;
                    WriteVerbose(string.Format("No application id provided - created new AD application with application id '{0}'", ApplicationId));
                    printPassword = true;
                }
            }

            CreatePSServicePrincipalParameters createParameters = new CreatePSServicePrincipalParameters
            {
                ApplicationId  = ApplicationId,
                AccountEnabled = true,
            };

            var shouldProcessMessage = string.Format("Adding a new service principal to be associated with an application " +
                                                     "having AppId '{0}' with no permissions.", createParameters.ApplicationId);

            if (!SkipRoleAssignment())
            {
                if (!this.IsParameterBound(c => c.Scope))
                {
                    Scope = string.Format("/subscriptions/{0}", subscriptionId);
                    WriteVerbose(string.Format("No scope provided - using the default scope '{0}'", Scope));
                }

                AuthorizationClient.ValidateScope(Scope, true);

                if (!this.IsParameterBound(c => c.Role))
                {
                    Role = "Contributor";
                    WriteVerbose(string.Format("No role provided - using the default role '{0}'", Role));
                }

                shouldProcessMessage = string.Format("Adding a new service principal to be associated with an application " +
                                                     "having AppId '{0}' with '{1}' role over scope '{2}'.", createParameters.ApplicationId, this.Role, this.Scope);
            }

            if (ShouldProcess(target: createParameters.ApplicationId.ToString(), action: shouldProcessMessage))
            {
                PSADServicePrincipalWrapper servicePrincipal = new PSADServicePrincipalWrapper(ActiveDirectoryClient.CreateServicePrincipal(createParameters));
                if (printPassword)
                {
                    servicePrincipal.Secret = Password;
                }
                else if (printUseExistingSecret)
                {
                    WriteVerbose(String.Format(ProjectResources.ServicePrincipalCreatedWithCredentials, ApplicationId));
                }
                WriteObject(servicePrincipal);
                if (SkipRoleAssignment())
                {
                    WriteVerbose("Skipping role assignment for the service principal.");
                    return;
                }

                WriteWarning(string.Format("Assigning role '{0}' over scope '{1}' to the new service principal.", this.Role, this.Scope));
                FilterRoleAssignmentsOptions parameters = new FilterRoleAssignmentsOptions()
                {
                    Scope = this.Scope,
                    RoleDefinitionName = this.Role,
                    ADObjectFilter     = new ADObjectFilterOptions
                    {
                        SPN = servicePrincipal.ApplicationId.ToString(),
                        Id  = servicePrincipal.Id.ToString()
                    },
                    ResourceIdentifier = new ResourceIdentifier()
                    {
                        Subscription = subscriptionId
                    },
                    CanDelegate = false
                };

                for (var i = 0; i < 6; i++)
                {
                    try
                    {
                        TestMockSupport.Delay(5000);
                        PoliciesClient.CreateRoleAssignment(parameters);
                        var ra = PoliciesClient.FilterRoleAssignments(parameters, subscriptionId);
                        if (ra != null)
                        {
                            WriteVerbose(string.Format("Role assignment with role '{0}' and scope '{1}' successfully created for the created service principal.", this.Role, this.Scope));
                            break;
                        }
                    }
                    catch (Exception)
                    {
                        // Do nothing
                    }
                }
            }
        }
        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                //safe gauard for login status, check if DefaultContext not existed, PSInvalidOperationException will be thrown
                var CheckDefaultContext = DefaultContext;

                if (this.ParameterSetName == SimpleParameterSet)
                {
                    CreateSimpleServicePrincipal();
                    return;
                }

                if (!this.IsParameterBound(c => c.EndDate))
                {
                    WriteVerbose(Resources.Properties.Resources.DefaultEndDateUsed);
                    EndDate = StartDate.AddYears(1);
                }

                if (this.IsParameterBound(c => c.ApplicationObject))
                {
                    ApplicationId = ApplicationObject.ApplicationId;
                    DisplayName   = ApplicationObject.DisplayName;
                }

                if (ApplicationId == Guid.Empty)
                {
                    string uri = "http://" + DisplayName.Trim().Replace(' ', '_');

                    // Create an application and get the applicationId
                    CreatePSApplicationParameters appParameters = new CreatePSApplicationParameters
                    {
                        DisplayName    = DisplayName,
                        IdentifierUris = new[] { uri },
                        HomePage       = uri
                    };

                    if (this.IsParameterBound(c => c.PasswordCredential))
                    {
                        appParameters.PasswordCredentials = PasswordCredential;
                    }
                    else if (this.IsParameterBound(c => c.CertValue))
                    {
                        appParameters.KeyCredentials = new PSADKeyCredential[]
                        {
                            new PSADKeyCredential
                            {
                                StartDate = StartDate,
                                EndDate   = EndDate,
                                KeyId     = Guid.NewGuid(),
                                CertValue = CertValue
                            }
                        };
                    }
                    else if (this.IsParameterBound(c => c.KeyCredential))
                    {
                        appParameters.KeyCredentials = KeyCredential;
                    }

                    if (ShouldProcess(target: appParameters.DisplayName, action: string.Format("Adding a new application for with display name '{0}'", appParameters.DisplayName)))
                    {
                        var application = ActiveDirectoryClient.CreateApplication(appParameters);
                        ApplicationId   = application.ApplicationId;
                    }
                }

                CreatePSServicePrincipalParameters createParameters = new CreatePSServicePrincipalParameters
                {
                    ApplicationId  = ApplicationId,
                    AccountEnabled = true
                };

                if (ShouldProcess(target: createParameters.ApplicationId.ToString(), action: string.Format("Adding a new service principal to be associated with an application having AppId '{0}'", createParameters.ApplicationId)))
                {
                    var servicePrincipal = ActiveDirectoryClient.CreateServicePrincipal(createParameters);
                    WriteObject(servicePrincipal);
                }
            });
        }