Unable to Access SharePoint using PowerShell - azure

I have registered an Application on Azure and I am trying to get an access token using the following command.
$Auth=Get-ODAuthentication -ClientId 01xex4x7-f0e2-xbx4-8aa3-1ac7a46c784c -AppKey "Xm1234~x555Sr-ATtpyCBOzkYiakI.PCVkEuBZ" -RedirectURI "http://localhost/login" -ResourceId "https://xyz.sharepoint.com/" -RefreshToken $LastAuth.refresh_token .
I am getting the following error.
Add-Member : Cannot bind argument to parameter 'Name' because it is an
empty string. At
C:\Users\Administrator\Documents\WindowsPowerShell\Modules\OneDrive\2.2.7\OneDrive.psm1:127
char:47
... thentication | add-member Noteproperty $element.split("=")[0] $elemen ..
However, when I save the command to a script and add a timeout, I am able to get the access token.
I have set the REDIRECT URI as http://localhost/login (Not an actual working URL). Can this be the reason. I tried to look this up but a little confused about the value this should have. Any pointers are greatly appreciated.

We have tested the same in our environment to access the sharepoint by using powershell and it works fine at our end. Below is the workaround :-
Register an application in Azure AD , Added redirect uri as http://localhost/ and enabled ID token .
Given the below permissions to our application and granted admin consent in Azure Ad.
Installed the one drive module by using Install-Module -Name OneDrive -Scope CurrentUser -force
Used the below command to get the access token after login with connect-azaccount , Ensure that you have provided all the permissions as mentioned above and added the correct resource ID of your sharepoint application and redirect uri as followed.
Cmdlt:-
$Auth=Get-ODAuthentication -ClientId "60xxxxxxxxxxxxxxxxx" -AppKey "3aXXXXXXXXXXXXXXXXXXXXXXXXXX=" -RedirectURI "http://localhost/" -ResourceId "https://mytest-admin.sharepoint.com/" -RefreshToken $LastAuth.refresh_token
OUTPUT DETAILS :-
POWERSHELL VERSION:
For more information please refer this GitHub| OneDrive for Business

Related

unable to authenticate to azure using powershell

we had an azure tenant.
we opened a new one, and passed our users to the new tenant and then added our users to the old tenants as guests.
Passing means that we deleted our users from the first tenant, then we migrated the domain to the new tenant and we created the users with the same properties in the new tenant.
since then every time we try to connect to azure using powershell with the commend Connect-azaccount -TenantId we get the following error:
Unable to acquire token for tenant '***' with error 'SharedTokenCacheCredential authentication unavailable. No account matching the specified username: *** tenantId: *** was found in the cache.'
does someone knows hoe to fix this?
thank you
we have tried every thing we found online.
we tries clear-azcontext, deleting the certificated from our machines, deleting powershell and reinstalling, etc...
Unable to acquire token for tenant xxx with error SharedTokenCacheCredential authentication unavailable. No account matching the specified username: xxx tenantId: xxx was found in the cache
The error usually occurs if the user is not present in the tenant you are trying to sign-in.
To check the error in detail, you can try debugging like below:
$DebugPreference = "Continue"
Connect-AzAccount -TenantID XXXX
Based on the debug details, you can check which Tenant is the user being connected to or any user details.
Try to connect with Subscription ID like below:
Connect-AzAccount -Subscription SubscriptionID -TenantId TenantID
Check if the user is having MFA enabled and try connecting with Global Admin account. And it might be the scenario where the account might be still cached in the local machine, so try if it works in another machine.
You can also make use of Device Authentication like below:
Connect-AzAccount -Tenant TenantID -UseDeviceAuthentication
Open the browser and enter the code:
Make sure to install the Az module like below:
Initially clear the cache and try to install by setting execution policy
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
Install-Module Az
Import-Module Az
Update-Module -Name Az
Check whether the user account in the Tenant has required permissions to the subscription.
Try to select the Context in PowerShell:
Get-AzContext -ListAvailable
Select-AzContext -Name Name
Or you can set context to the SubscriptionID by including TenantID:
Set-AzContext -Subscription $subscription -Tenant $tenantId | Out-null
If still the issue persists, it might be some environment problem while migrating the domain.
For me the problem seemed to be related to using a "legacy" account (or whatever they're called). Making and using a new account seemed to resolve the issue for me.

managed identity for this assignment does not have the appropriate permissions to remediate these resources. Edit Assignment page and re-save it

I have a requirement of creating policy assignment from policy initiative and do remediation. I can create assignment using the below command.
$newRgAssignment = New-AzPolicyAssignment -Name $assigName -PolicySetDefinition $policySet -PolicyParameterObject $Params -AssignIdentity -Location 'westus' -scope $rgscope -DisplayName $assigName
In this I can create assignment successfully. while trying to remediation manually in I can see the below error message in azure portal .
The managed identity for this assignment does not have the appropriate permissions to remediate these resources. To add these permissions, go to the Edit Assignment page for this Policy and re-save it.
I tried creating a policy assignment by passing SystemAssigned identity type but ran into same problem.
I have left with only one option that is UserAssigned identity type. To pass this parameter we need to get the assigned user identity . To get the user identity I used the below commands
Set-AzContext -Subscription 'XYZ-123-ABC'
$UserAssignedIdentity = Get-AzUserAssignedIdentity
But no use.
Can any one help me on this issue. Any help can be appriciated.
Thank you.
TenantId 'xxxx-xxxx-xxxx-xxxx' contains more than one active
subscription. First one will be selected for further use. To select
another subscription, use Set-AzContext. This is not any error. Its a
warning. Get-AzUserAssignedIdentity command returning null.
We have tried with below cmd after installing module Az.ManagedSericeIdentity and can able to get the results.
Warning you might receive but after Set-AzContext -Subscription 'XYZ-123-ABC'
it will be logged into the correct subscription you wanted to.
After successfully login type $UserAssignedIdentity even if you have user role to that subscription.
For more information please refer the below links:-
MS DOC| Get-AzUserAssignedIdentity
SO THREAD .

Permissions error upon running Add-DistributionGroupMember PS cmdlet on Exchange Online

I'm currently trying to automate the user creation in Azure AD, and addition to a distribution group in Exchange Online using a PowerShell script. I've followed this guide for that - I've set up an app registration with a certificate and that's how I'm authenticating to both Azure AD and Exchange Online - without human intervention.
The specific Exchange cmdlet I'm running in the script (for the EXO part) is Add-DistributionGroupMember -member "user#domain.com" -identity "dlist" -BypassSecurityGroupManagerCheck, and once I run it I receive the following error output:
Active Directory operation failed on XXXXXXXXXXXXXXX.XXXXXXXXXXX.PROD.OUTLOOK.COM. This error is not retriable. Additional information: Insufficient access rights to perform the operation.
Active directory response: 00002098: SecErr: DSID-XXXXXXXX, problem 4003 (INSUFF_ACCESS_RIGHTS), data 0
+ CategoryInfo : NotSpecified: (:) [Add-DistributionGroupMember], ADOperationException
+ FullyQualifiedErrorId : [Server=XXXXXXXXXXXXX,RequestId=8ac3130a-4bbe-41a0-b062-4768b6f51234,TimeStamp=1/3/2021 2:18:13 PM] [FailureCategory=Cmdlet-ADOperationException] XXXXXXX,Microsoft.Exchange.Management.RecipientTasks.AddDistribu
tionGroupMember
+ PSComputerName : outlook.office365.com
Other cmdlets such as
Get-Mailbox work correctly, but this specific one is giving me problems constantly. I've tried giving all API permissions I can think of in Azure to the application, both Delegated and Application permissions, and yet I'm still facing the error. Here's the current full list and I've had no success whatsoever:
I also tried replacing some of the Delegated permissions with Application permissions to no avail either. I tried assigning a variety of roles to the application as mentioned in the article too and every single time I get that Insufficient access rights to perform the operation error.
Could someone tell me why? Where and how am I supposed to grant the necessary permissions for the app to add a user to a distribution (mailing) list?
I've been searching around and found no answer to it for that last few days. Any help would be greatly appreciated.
Based on my test, adding Exchange.ManageAsApp Application permission and assigning Exchange Service administrator role is enough.
Create the AAD app with adding Exchange.ManageAsApp Application permission.
$appName = 'Exo_V2_App'
$api = (Get-AzureADServicePrincipal -Filter "AppID eq '00000002-0000-0ff1-ce00-000000000000'")
$permission = $api.AppRoles | Where-Object { $_.Value -eq 'Exchange.ManageAsApp' }
$apiPermission = [Microsoft.Open.AzureAD.Model.RequiredResourceAccess]#{
ResourceAppId = $api.AppId ;
ResourceAccess = [Microsoft.Open.AzureAD.Model.ResourceAccess]#{
Id = $permission.Id ;
Type = "Role"
}
}
$myApp = New-AzureADApplication -DisplayName $appName -ReplyUrls 'http://localhost' -RequiredResourceAccess $apiPermission
$mySP = New-AzureADServicePrincipal -AppID $myApp.AppID
$myApp | Format-List DisplayName,ObjectID,AppID
Assign the service principal to Exchange Service administrator role.
$directoryRole = 'Exchange Service Administrator'
$RoleId = (Get-AzureADDirectoryRole | Where-Object {$_.displayname -eq $directoryRole}).ObjectID
Add-AzureADDirectoryRoleMember -ObjectId $RoleId -RefObjectId $mySP.ObjectID -Verbose
You can try to create a new clean Azure AD app without adding additional configuration to have a test.
If I am not wrong, you should be part of the ManagedBy of the group before adding the members.
Step 1 :
First execute one of the below commands :
Set-DistributionGroup <NameOfGroup> -ManagedBy "<Your Alias>" -BypassSecurityGroupManagerCheck
Or :
Set-DistributionGroup Accounting -ManagedBy #{Add="< Your Alias>"} -BypassSecurityGroupManagerCheck
Step 2 :
Then execute the command to add the user to the group.
Add-DistributionGroupMember -Identity <NameOfGroup> -Member user#contoso.com
We had a very similar issue that was resolved by updating the Exchange Online PowerShell module version from 2.0.5 to 3.1.0.
Command to check version:
Get-InstalledModule ExchangeOnlineManagement | Format-List Name,Version,InstalledLocation
Command to update to latest version:
Update-Module -Name ExchangeOnlineManagement

Azure Devops: value cannot be null, parameter token

I am running an Azure Powershell task in Azure DevOps.
Inside the script I use the following command
Get-AzureRmADUser -UserPrincipalName $adusernameNewPermission
But my Release pipeline fails with following error code
##[error]Value cannot be null.
Parameter name: token
First I thought that the command didn't have the right context or enough permission so I've added the defaultprofile.
Get-AzureRmADUser -DefaultProfile (Get-AzureRmContext) -UserPrincipalName $adusernameNewPermission
The GetAzureRmContext did go to the right context if I print the output of that command.
The command itself didn't had any problem when running locally (with my own user account) So the only reason I think its heading is that the service connection doesn't have the right to perform that action. But my user account has the least permissions on the tenant whilst the service connnection in azure devops has much more permissions.
It's driving me crazy where the problem lays with this one. Which token does it mean ? No reasonable error message :(
Does someone encounter the same problem or knows what I am missing ?
PS: the $adusernameNewPermission variable works like I said the exact same code runs perfectly on my local machine with the only difference being the user that is logged in.
Did you try using Get-azureaduser instead? This is a command that requires the function to be authenticated against Azure AD.
$azurePassword = ConvertTo-SecureString $env:client_secret -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($env:clientid , $azurePassword)
Connect-AzAccount -Credential $psCred -TenantId $env:tenantid -ServicePrincipal
If you're using the Script Type of "Script File Path," check that you're not trying to pass in any arguments (such as -token).
I'd try 2 things to get back to basics. This will let you know if it is actually the AzDO Service Principal or not and the type of object to use in the pipeline.
Test the functionality of the command in its simplest form and run it with the account as a string:
Get-AzureRmADUser -UserPrincipalName "achahbar#stankoverflow.com"
#OR
$UPN = "achahbar#stankoverflow.com"
Get-AzureRmADUser -UserPrincipalName $UPN
Assuming this works and depending on what your variable contains you simply need to pass the the UPN/Email object into the command:
Get-AzureRmADUser -UserPrincipalName $adusernameNewPermission.UPN
If this doesn't work pdate your task to Version 4 (Preview) and update your commands to Get-AzADUser and test step 1. again
I fixed this issue by changing the service connection in Azure DevOps that was created with a managed identity. I created a new service connection with a service principal and this doesn't gave me any errors about the value token. Hope any person who looks for this issue in the future got an answer by this.

Running New-AzureRmResourceGroupDeployment from within a Function App

I need to wire up a stateless worker ad-hoc to perform a long running job based off a user action that self destructs when its done. I am trying to run New-AzureRmResourceGroupDeployment from within a PoSh Function App and cannot figure out how to authenticate to Azure from within the PoSh script.
I tried this:
$accountName = "myID#mydomain.com"
$pwd = ConvertTo-SecureString "password" -AsPlainText -Force
$cred = new-object PSCredential($accountName, $pwd)
Add-AzureRmAccount -Credential $cred
New-AzureResourceGroupDeployment -ResourceGroupName yadda yadda
And I get an error message that I need to use an Organization ID (which I am, our Azure AD is federated and we use AD Sync (and SiteMinder w/o WS-* if that matters)):
Add-AzureRmAccount : -Credential parameter can only be used with Organization ID credentials. For more information, please refer to http://go.microsoft.com/fwlink/?linkid=331007&clcid=0x409 for more information about the difference between an organizational account and a Microsoft account.
I tried "Login-AzureRMAccount -Credential $cred" with similar results.
If I do the Add- or Login- cmdlets from a PoSh window on my local machine (which is member joined to AD) with the -Credential flag I get a similar error. If I run the cmdlets without the credential I am prompted for credentials through an interactive ID/PW window (I do not have to enter my password once I type in my ID).
Does anyone know how I can do the authentication? I would be okay with authenticating like above, some sort of pass through credential from our web layer, or even an Option C I don't know about.
You will need to use service principal for authentication. A sample with instructions can be found here.
Azure Function role like permissions to Stop Azure Virtual Machines
For that you would need to use Service Principal auth. I don't think there is any sense of copypasting Azure Doc's to this answer, just consult this document:
https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-authenticate-service-principal

Resources