Connect-AzureAD : parsing_wstrust_response_failed: Parsing WS-Trust response failed - azure

I am getting the following below error when every time i run my script to connect to Azure Ad via Powershell
Connect-AzureAD : One or more errors occurred.: parsing_wstrust_response_failed: Parsing WS-Trust response failed
At C:\Azure-AD\Azure-Connect.ps1:10 char:1
+ Connect-AzureAD -TenantId $TenantId -credential $MyCredential
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : AuthenticationError: (:) [Connect-AzureAD], AadAuthenticationFailedException
+ FullyQualifiedErrorId : Connect-AzureAD,Microsoft.Open.Azure.AD.CommonLibrary.ConnectAzureAD
Below is the script i have created
$TenantId = ""
$SecFile = "C:\Azure-AD\Password.txt"
$SecUser = "C:\Azure-AD\UserName.txt"
$MyCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $SecUser,
(Get-Content $SecFile | ConvertTo-SecureString)
Connect-AzureAD -TenantId $TenantId-credential $MyCredential
I am using the following line to generate to encrypt my password
(Get-Credential).Password | ConvertFrom-SecureString | Out-File "C:\AzureAD\Password.txt"
Any solutions on how I can fix the errors and connect to Azure Ad via Powershell

I have tested in my environment.
Please use the below script :
$tenantID = ""
$secfile = "C:\Azure-AD\Password.txt";
$secuser = "C:\Azure-AD\UserName.txt";
$username = Get-Content $secuser;
$password = Get-Content $secfile | ConvertTo-SecureString -AsPlainText -Force;
$MyCredential = New-Object Management.Automation.PSCredential ($username, $password);
Connect-AzureAD -TenantId $tenantID -credential $MyCredential

Related

How do I connect to Azure through PowerShell Modules, using the Service principal of a Registered App?

I need to create a powershell script that queries Azure Resources.
What I have is an App Registration.
App Registrations give us the following information:
# --- APP REGISTRATION OUTPUT
# appId = "***** APP ID *******"
# displayName = "**** APP Name **** "
# password = "***** SECRET *******"
# tenant = "**** TENANT ID *****"
I need to use these credentials to now access Azure via PowerShell script.
I have tried the following:
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $ApplicationId, $SecuredPassword
Connect-AzAccount -ServicePrincipal -TenantId $TenantId -Credential $Credential
But I get an error:
… Account -ServicePrincipal -TenantId $TenantId -Credential $Credential
| ~~~~~~~~~~~
| Cannot bind argument to parameter 'Credential' because it is null.
I don't think what Im doing is abnormal. App Registrations give us the ability to allow Apps (PowerShell Apps!) to interact with a given tenant. Or am I mistaken?
I don't want the app to login every time using an account (i.e. To have a browser window open whenever the script runs).
What am I doing wrong?
You have missed converting your password into secure string. You could verify that in your $credential variable.
$ApplicationId = "0000-0000-0000-0000"
$Password = "000000000000000"
$TenantId = "0000-0000-000-000"
$subscriptionId = "0000-0000-0000-0000"
$SecuredPassword = ConvertTo-SecureString -AsPlainText $Password -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $ApplicationId, $SecuredPassword
Connect-AzAccount -ServicePrincipal -TenantId $TenantId -Credential $Credential
$sub = Get-AzSubscription -SubscriptionId $subscriptionId
Set-AzContext -Subscription $sub
I have reproduced in my environment and below script worked for me :
$appId ="53f3ed85-70c1c2d4aeac"
$pswd="55z8Q~_N9SRajza8R"
$t = "72f988bf-cd011db47"
[ValidateNotNullOrEmpty()]$pswd="55z8BU4oik.kVrZWyaK8R" $sp = ConvertTo-SecureString -String $pswd -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $appId, $sp
Connect-AzAccount -ServicePrincipal -TenantId $t -Credential $Credential
Output:
You need to convert the secret value(password) into secured password like above, then it will work as mine worked.

Azure Runbook | Sending attachments from my Azure Storage Account in Transactional Emails

I have an Azure Runbook script set up for transaction emails, the SMTP server details, & the from and to emails redacted for security.
For some reason, PowerShell is not seeing the file with which I want to send as an attachment, can anyone see where I am going wrong?
I have included a screenshot as proof that I have the correct file (I believe they're called 'blobs'?) name, storage account name and container name
Below is the Runbook PowerShell script, along with the error messages upon testing the email.
All the best,
===================RUNBOOK POWERSHELL CODE===========================
$Username ="xxx"
$Password = ConvertTo-SecureString "xxx" -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $Username, $Password
$SMTPServer = "xxx"
$EmailFrom = "xxx"
[string[]]$EmailTo = "xxx"
$Subject = "xxx"
# Setting the Azure Storage Context,recommedation is to read sastoken from Runbook assets for security purpose.
$context = New-AzureStorageContext -StorageAccountName "expertadvisers" -SasToken "?sv=2019-12-12&ss=bfqt&srt=c&sp=rwdlacupx&se=2021-01-20T17:01:17Z&st=2021-01-20T09:01:17Z&spr=https&sig=PpozvhXnD6k4knwLLpyJvMF0vpnSZATabreYTzr0s2k%3D"
#Get the blob contents from storage container and store it local destination .
Get-AzureStorageBlob -Container "notificationcontainer" -Blob "test_file.docx" -Context $context | Get-AzureStorageBlobContent -force -Destination .
#Get contents of the file
[string[]] $attachment = "test_file.docx"
$Body = "TEST MESSAGE"
Send-MailMessage -smtpServer $SMTPServer -Attachment $attachment -Credential $credential -Usessl -Port 587 -from $EmailFrom -to $EmailTo -subject $Subject -Body $Body -Priority High -DeliveryNotificationOption OnSuccess -BodyAsHtml
Write-Output ("Email sent succesfully.")
===================ERROR MESSAGE===========================
Get-AzureStorageBlob : The remote server returned an error: (403) Forbidden. HTTP Status Code: 403 - HTTP Error
Message: Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly
including the signature.
At line:19 char:1
+ Get-AzureStorageBlob -Container "notificationcontainer" -Blob "test_f ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzureStorageBlob], StorageException
+ FullyQualifiedErrorId :
StorageException,Microsoft.WindowsAzure.Commands.Storage.Blob.Cmdlet.GetAzureStorageBlobCommand
Send-MailMessage : Could not find file 'C:\Temp\pyxr0xjf.rej\test_file.docx'.
At line:32 char:1
+ Send-MailMessage -smtpServer $SMTPServer -Attachment $attachment -Cre ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Send-MailMessage], FileNotFoundException
+ FullyQualifiedErrorId : System.IO.FileNotFoundException,Microsoft.PowerShell.Commands.SendMailMessage
Regarding the issue, please refer to the following steps
Create SAS token via protal
Script
$Username =""
$Password = ConvertTo-SecureString "" -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $Username, $Password
$Subject = "test"
$To=""
$Body = "This is an automated mail send from Azure Automation relaying mail using Office 365."
$Context = New-AzureStorageContext -StorageAccountName "andyprivate" -SasToken "<the sas token you created in step1>"
$a=Get-AzureStorageBlobContent -Container "output" -Blob "test.txt" -Context $Context
$attachment = $a.Name
Send-MailMessage `
-To $To `
-Subject $Subject `
-Body $Body `
-UseSsl `
-Port 587 `
-SmtpServer 'smtp.office365.com' `
-From $Username `
-Attachments $attachment `
-BodyAsHtml `
-Credential $credential

Login-AzureRmAccount : -Credential parameter can only be used with Organization ID credentials

While logging into the Azure account through powershell, I am getting the error -
Login-AzureRmAccount : -Credential parameter can only be used with Organization ID credentials.
I need to understand when this error comes?
[string]$TenantID,
[string]$ApplicationID,
[string]$SecretKey,
[string]$ProcessInstanceID,
[string]$Endpoint
)
$securePassword = ConvertTo-SecureString -String $SecretKey -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($ApplicationID, $securePassword)
$profilePath = "D:\" + $ProcessInstanceID + "_azureProfile.json"
Clear-AzureRmContext -Scope Process
$azureok = $null
while ($azureok -eq $null) {
if($Endpoint -match "china"){
Connect-AzureRmAccount -ServicePrincipal -TenantId $TenantID -Credential $cred -Environment AzureChinaCloud -ea silentlycontinue -wa silentlycontinue -ev errorvar | out-null
}
else{
Connect-AzureRmAccount -ServicePrincipal -TenantId $TenantID -Credential $cred -ea silentlycontinue -wa silentlycontinue -ev errorvar | out-null
}
if ($errorvar.exception -ne $null) {
if ($errorvar.exception.message -eq "An error occurred while sending the request.") {
Start-sleep -s 10
$error.clear()
} else {
break
}
} else {
$azureok = $true
}
}
Save-AzureRmContext -Path $profilePath ````
Error message -
Login-AzureRmAccount : -Credential parameter can only be used with Organization ID credentials.

Azure Analytics Database with automate Backup

The powershell is used to automate the backup of AAS instance.
The instance have Multi-factor authentication and I think that is the problem.
Powershell:
$TenantId = "TenentID"
$Cred = Get-AutomationPSCredential -Name 'SSASModelBackup'
$Server = "ServerName"
$RolloutEnvironment = "location.asazure.windows.net"
$ResourceGroup = "ReourceGroupName"
#Create Credentials to convertToSecureString
$applicationId = "applicationId "
$securePassword = "securePassword " | ConvertTo-SecureString -AsPlainText -Force $Credential = New-Object
-TypeName System.Management.Automation.PSCredential -ArgumentList $applicationId, $securePassword
#Define the list of AAS databases
$asDBs = #('database1','database2')
Write-Output "Logging in to Azure..."
#Add-AzureAnalysisServicesAccount -Credential $Credential -ServicePrincipal -TenantId $TenantId -RolloutEnvironment $RolloutEnvironment
ForEach($db in $asDBs)
{
Write-Output "Starting Backup..."
Backup-ASDatabase `
–backupfile ($db +"." + (Get-Date).ToString("ddMMyyyy") + ".abf") `
–name $db `
-server $Server `
-Credential $Cred
Write-Output "Backup Completed!"
}
You are correct that the issue is with multi-factor authentication. Since the point of multi-factor is the require interaction with a secondary source like your phone there is no way to automate the process.
I would suggest that you look into using service principle authentication for the purpose of taking backups. By using a service principle to your server you can allow for automated tasks to run without 2-factor while minimizing the security risk.

Export SQL Azure db to blob - Start-AzureSqlDatabaseExport : Cannot convert AzureStorageContainer to AzureStorageContainer

I am using this code found on stack , and all connections are correct.
Import-Module Azure
Import-Module Azure.Storage
Get-AzureRmSubscription –SubscriptionName “Production” | Select-AzureRmSubscription
# Username for Azure SQL Database server
$ServerLogin = "username"
# Password for Azure SQL Database server
$serverPassword = ConvertTo-SecureString "abcd" -AsPlainText -Force
# Establish credentials for Azure SQL Database Server
$ServerCredential = new-object System.Management.Automation.PSCredential($ServerLogin, $serverPassword)
# Create connection context for Azure SQL Database server
$SqlContext = New-AzureSqlDatabaseServerContext -FullyQualifiedServerName “myspecialsqlserver.database.windows.net” -Credential $ServerCredential
$StorageContext = New-AzureStorageContext -StorageAccountName 'prodwad' -StorageAccountKey 'xxxxx'
$Container = Get-AzureStorageContainer -Name 'automateddbbackups' -Context $StorageContext
$exportRequest = Start-AzureSqlDatabaseExport -SqlConnectionContext $SqlContext -StorageContainer $Container -DatabaseName 'Users' -BlobName 'autobackupotest.bacpac' -Verbose -Debug
I am getting this error. I have spent hours on this.
Start-AzureSqlDatabaseExport : Cannot bind parameter 'StorageContainer'. Cannot convert the
"Microsoft.WindowsAzure.Commands.Common.Storage.ResourceModel.AzureStorageContainer" value of type
"Microsoft.WindowsAzure.Commands.Common.Storage.ResourceModel.AzureStorageContainer" to type
"Microsoft.WindowsAzure.Commands.Common.Storage.ResourceModel.AzureStorageContainer".
At line:31 char:99
+ ... SqlConnectionContext $SqlContext -StorageContainer $Container -Databa ...
+ ~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Start-AzureSqlDatabaseExport], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.WindowsAzure.Commands.SqlDatabase.Database.Cmdlet.StartAzureSqlDatabaseExport
I am using AzureRM 3.8.0
According to your description and codes, If you want to start a new sqldatabase export.I suggest you could try below codes. It will work well.
$subscriptionId = "YOUR AZURE SUBSCRIPTION ID"
Login-AzureRmAccount
Set-AzureRmContext -SubscriptionId $subscriptionId
# Database to export
$DatabaseName = "DATABASE-NAME"
$ResourceGroupName = "RESOURCE-GROUP-NAME"
$ServerName = "SERVER-NAME"
$serverAdmin = "ADMIN-NAME"
$serverPassword = "ADMIN-PASSWORD"
$securePassword = ConvertTo-SecureString -String $serverPassword -AsPlainText -Force
$creds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $serverAdmin, $securePassword
# Generate a unique filename for the BACPAC
$bacpacFilename = $DatabaseName + (Get-Date).ToString("yyyyMMddHHmm") + ".bacpac"
# Storage account info for the BACPAC
$BaseStorageUri = "https://STORAGE-NAME.blob.core.windows.net/BLOB-CONTAINER-NAME/"
$BacpacUri = $BaseStorageUri + $bacpacFilename
$StorageKeytype = "StorageAccessKey"
$StorageKey = "YOUR STORAGE KEY"
$exportRequest = New-AzureRmSqlDatabaseExport -ResourceGroupName $ResourceGroupName -ServerName $ServerName `
-DatabaseName $DatabaseName -StorageKeytype $StorageKeytype -StorageKey $StorageKey -StorageUri $BacpacUri `
-AdministratorLogin $creds.UserName -AdministratorLoginPassword $creds.Password
$exportRequest
# Check status of the export
Get-AzureRmSqlDatabaseImportExportStatus -OperationStatusLink $exportRequest.OperationStatusLink
Then you could use Get-AzureRmSqlDatabaseImportExportStatus to see the details information, like below:
I got the same problem after updating some powershell packages which I do not remember exactly. After the update my scripts started to fail.
My solution is :
Install the latest AzureRM from nuget via powershell
Use the other overload of Start-AzureSqlDatabaseExport which utilizes the parameters
-StorageContainerName and -StorageContext rather than -StorageContainer
It looks like if you pass the parameters to the function it will create the container object internally without crashing.

Resources