Get-ShardMapManager without Username and Password - database

Is it possible to call Get-ShardMapManager when creating a new shard map manager without involving username and password (through hardcoding or storing the values in key vault)
Here is the code that I currently have in powershell
$ShardMapManager = Get-ShardMapManager -Username $DbUsrId -Password $DbPwd
can i use token or something like that? just whatever that is not involving username and password? thanks

No, you can't. From the source code of Get-ShardMapManager, UserName and Password are all Mandatory=$true.
In this case, if you want to avoid using them just because of the security issue, you can use azure keyvault to store them via Set-AzKeyVaultSecret as you mentioned. Retrieve them in the commands, then pass them to Get-ShardMapManager, just user/service principal that added to the access policy of the keyvault is able to get them(or has the Key Vault Administrator if you select Azure role-based access control in Access policies blade of the keyvault).
Make sure you have installed Az powershell module, then use the command below.
Connect-AzAccount
$DbUsrId = Get-AzKeyVaultSecret -VaultName "keyvaultname" -Name "username" -AsPlainText
$DbPwd = Get-AzKeyVaultSecret -VaultName "keyvaultname" -Name "password" -AsPlainText
$ShardMapManager = Get-ShardMapManager -Username $DbUsrId -Password $DbPwd

Related

Check if user exist in AD using Azure CLI

I have installed the Azure CLI to connect to the tenant.
Now I want to import a CSV containing several emails to get cross checked if they exist in the AD.
There a tons of ways to do it with 'Get-ADUser' (which I'm not using since I'd need to set up the server locally) but I could not find any with Azure CLI.
Anyone managed to do this?
This is the list of commands to manage users with AZ CLI
https://learn.microsoft.com/en-us/cli/azure/ad/user?view=azure-cli-latest
Also, there is a PowerShell module that allows you to manage the user in your Azure AD.
https://learn.microsoft.com/en-us/powershell/module/azuread/?view=azureadps-2.0#users
You can get all the ad users by using below command:
Get-AzureADUser -All $true
If you want to know if the user exists or not follow below commands:
XX- example display name
Step-1
$s= Get-AzureADUser -All $true
Step-2
if($s.DisplayName -eq "XX")
{
Write-Host "Present"
} else
{
Write-Host "Not Present"
}
References taken from:
https://learn.microsoft.com/en-us/powershell/module/az.resources/get-azaduser?view=azps-8.3.0#syntax

How to Connect to azuread module non-interactively when MFA is enabled?

I need to connect to AD in azure function app using powershell script. (as it is in function i need to do it without prompt) I am trying this:
Import-Module D:\home\site\wwwroot\HttpTrigger1\AzureAD\AzureAD.psd1 -UseWindowsPowershell
$creds = Connect-AzureAD -TenantId $tenantId -Credential $Credential
In my function app I have enabled Authentication through Log in with Azure Active Directory.
Is there a way to use that authentication in powershell script to connect to azuread module. I mean the user clicks on the function-app url, logs-in with their credentials and that authentication can be used in the script for connect-azuread. The current script is not working as MFA is enabled, which cannot be removed as per our use-case.
Use-case: I have an application in the form of an ARM template that would be deployed as a managed application.
The ARM template is supposed to deploy a set of resources on the tenant of the user, whoever purchases the app. But I need "client id"
and "client secret" of the application registration on user/customer's tenant with O365 mgt api permissions, as input to
my mainTemplate.json.
This App registration is a one-time thing and is not possible through ARM template, that is why I am trying to achieve the above via
powershell. I am creating a powershell function-app, enabled Authentication through Log in with Azure Active Directory.
Idea behind this approach is that at the time of purchasing the app, while filling-in other details(like Resource group name and region) at the UI(created by createUIDefinition.json), the user clicks on the function app link,
logs-in and the script runs in the background. The script should be able to create the app registration at the user's tenant and provide
back the client id and client secret of that app reg.
Unfortunately No !
If MFA is enabled, you will not be able to login non-interactively. This is kind of intentional considering to make it more secure. You cannot as well pass along the authentication.
The workaround for this you could possibly make use of the Azure Service Principal.Get the function authenticated and make the Azure Service Principal to do the job.
What Are Azure Service Principal ?
Service principals are non-interactive Azure accounts. Like other user accounts, their permissions are managed within Azure Active Directory.
Sharing some reference articles to get a deeper insight on the Azure Service Principal:
Creating the Service Principal (The creation is one time process)
https://learn.microsoft.com/en-us/azure/active-directory/develop/howto-create-service-principal-portal#app-registration-app-objects-and-service-principals
Creating the Service Principal through Powershell
https://learn.microsoft.com/en-us/azure/active-directory/develop/howto-authenticate-service-principal-powershell#create-service-principal-with-self-signed-certificate
Authenticating the Service Principal
https://learn.microsoft.com/en-us/powershell/azure/authenticate-azureps?view=azps-5.1.0
Coming back to your scenario, to execute Connect-AzureAD with out the interactive login using the service principal you could use the below snippet
# Login to Azure AD PowerShell With Admin Account
Connect-AzureAD
# Create the self signed cert
$currentDate = Get-Date
$endDate = $currentDate.AddYears(1)
$notAfter = $endDate.AddYears(1)
$pwd = ""
$thumb = (New-SelfSignedCertificate -CertStoreLocation cert:\localmachine\my -DnsName com.foo.bar -KeyExportPolicy Exportable -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" -NotAfter $notAfter).Thumbprint
$pwd = ConvertTo-SecureString -String $pwd -Force -AsPlainText
Export-PfxCertificate -cert "cert:\localmachine\my\$thumb" -FilePath c:\temp\examplecert.pfx -Password $pwd
# Load the certificate
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate("C:\temp\examplecert.pfx", $pwd)
$keyValue = [System.Convert]::ToBase64String($cert.GetRawCertData())
# Create the Azure Active Directory Application
$application = New-AzureADApplication -DisplayName "test123" -IdentifierUris "https://test123"
New-AzureADApplicationKeyCredential -ObjectId $application.ObjectId -CustomKeyIdentifier "Test123" -StartDate $currentDate -EndDate $endDate -Type AsymmetricX509Cert -Usage Verify -Value $keyValue
# Create the Service Principal and connect it to the Application
$sp=New-AzureADServicePrincipal -AppId $application.AppId
# Give the Service Principal Reader access to the current tenant (Get-AzureADDirectoryRole)
Add-AzureADDirectoryRoleMember -ObjectId 5997d714-c3b5-4d5b-9973-ec2f38fd49d5 -RefObjectId $sp.ObjectId
# Get Tenant Detail
$tenant=Get-AzureADTenantDetail
# Now you can login to Azure PowerShell with your Service Principal and Certificate
Connect-AzureAD -TenantId $tenant.ObjectId -ApplicationId $sp.AppId -CertificateThumbprint $thumb
Short Explanation of the code :
The above script creates Service Principal, grants a Read Access at the tenant level and connects to the Azure AD at the end using the created Service Principal.

Assigning Custom Azure AD Role to a Security Group

I've created a custom Azure AD role for the purpose of reading service principals within the directory. This is so users can troubleshoot without needing to find additional support. However, I'm not able to assign this custom role to an entire security group. How can I assign this role to all users within a group?
You could use the powershell to assign this role to all users in this group, try the script below.
First, you need to install the AzureADPreview powershell module.
Install-Module -Name AzureADPreview
Connect-AzureAD
$members = Get-AzureADGroupMember -ObjectId "<ObjectId of the Security Group>"
$roleDefinition = Get-AzureADMSRoleDefinition -Filter "displayName eq '<Custom role name>'"
# Get app registration and construct resource scope for assignment.
$appRegistration = Get-AzureADApplication -Filter "displayName eq 'joyttt'"
$resourceScope = '/' + $appRegistration.objectId
foreach($member in $members){
New-AzureADMSRoleAssignment -DirectoryScopeId $resourceScope -RoleDefinitionId $roleDefinition.Id -PrincipalId $member.ObjectId
}
Reference - https://learn.microsoft.com/en-us/azure/active-directory/users-groups-roles/roles-create-custom#assign-the-custom-role-using-azure-ad-powershell

How to add an AAD group with datawrite and dataread permissions to an Azure DB through PowerShell

I have an Azure SQL Server with an SQL database. I would like to add an AAD Group with datawrite and dataread permissions to this database through PowerShell.
I have no idea how to do this. Can anyone help?
Adding a user to a role is usually accomplished with SQL Statements. This is how this would be done with SQL.
CREATE USER [group name]
FROM external provider
DEFAULT_SCHEMA dbo
Once the user has been added, you can then add them to a group by issuing the following statements;
ALTER ROLE db_datareader ADD MEMBER [group_name]
ALTER ROLE db_datawriter ADD MEMBER [group_name]
Note, within SSMS, you must be in the context of the database you want to add the user to. Azure SQL does not support USE statements, so ensure you selected the correct database.
To do it through powershell, you would probably want to use the following CmdLet, Add-RoleMember, but I have not used these CmdLets with Azure SQL Server before.
This is one way to add users to a SQL database via Powershell;
$Instance = $ENV:AzureSQLServer + ".database.windows.net"
$Query = "CREATE USER [$ENV:AdUser] FROM EXTERNAL PROVIDER"
$ConnString = "Server=" + $Instance + ";Database=master;Authentication=Active Directory Password;UID=" + $Env:SqlAdminUser + ";Password=" + $Env:SqlAdminPass + ";Trusted_Connection=false;Encrypt=True;Connection Timeout=30;"
Invoke-SQlCmd -ConnectionString $ConnString -Query $Query
We use this script in a PowerShell task in Jenkins to add users to databases. The Statements could be modified to also add the users to the appropriate roles as well.
I assume that you want to set AAD Group as AAD admin for your SQL database.
With this scenario, you can use Set-AzureRmSqlServerActiveDirectoryAdministrator:
Set-AzureRmSqlServerActiveDirectoryAdministrator -ResourceGroupName "ResourceGroup01" -ServerName "Server01" -DisplayName "DBAs" -ObjectId "40b79501-b343-44ed-9ce7-da4c8cc7353b"
Result:
ResourceGroupName ServerName DisplayName ObjectId
----------------- ---------- ----------- --------
ResourceGroup01 Server01 DBAs 40b79501-b343-44ed-9ce7-da4c8cc7353b
NOTE:
You can only set the AAD Group with securtiy enabled.
Please let me know if this helps!
You first have to create an ADD group using e. g. the New-AzureADGroup cmdlet that is part of the AzureAD module.
Then you have to assign the desired role to your desired resource (e. g. the SQL DB Contributor role to your DB Server) using the New-AzureRmRoleAssignment cmdlet.
Further reading: Manage role-based access control with Azure PowerShell

How do I create a new Login using SQL Server PowerShell Provider and/or SMO?

I have a PowerShell script which creates a new SQL Server database. This is going to be a content database for a SharePoint 2010 implementation.
Once created I need to set the DBO to be my SharePoint farm account and I need to assign permissions to some other service accounts.
Does anyone have an idea of how to do this using SMO and the PowerShell Provider for SQL Server?
Setting the db owner is simply enough:
PS SQLSERVER:\SQL\MyServer\MyInstance\Databases\MyDatabase> $db = get-item .
PS SQLSERVER:\SQL\MyServer\MyInstance\Databases\MyDatabase> $db.SetOwner('sa')
PS SQLSERVER:\SQL\MyServer\MyInstance\Databases\MyDatabase> $db.alter()
#These two steps aren't necessary, but if you want to see the change
PS SQLSERVER:\SQL\MyServer\MyInstance\Databases\MyDatabase> $db.Refresh()
PS SQLSERVER:\SQL\MyServer\MyInstance\Databases\MyDatabase> $db.Owner
Assigning permissions is little tricky and of course there are multiple ways to assign a permissions. It would help if you described what permissions you want to assign (database, object, built-in role, server-level, schema, etc.). Here's how you create a database user and assign object permissions:
$user = new-object ('Microsoft.SqlServer.Management.Smo.User') 'MyDatabase', 'MyUser'
$user.Login = 'MyUser'
$user.DefaultSchema = 'dbo'
$user.Create()
PS SQLSERVER:\SQL\MyServer\MyInstance\Databases\MyDatabase\tables> $tbl = get-childitem | where {$_.name -eq 'mytable'}
$tbl.Grant('SELECT','myUser')

Resources