Error on: Connect-MgGraph -AccessToken $token -Scopes "User.ReadWrite.All" - powershell

I'm able to connect if I do this:
Connect-MgGraph -AccessToken $token
Remove-MgUserMessage -UserId $email -MessageId $item.id
but I'm getting unauthorized errors when trying to delete an email.
I tried this as well:
Connect-MgGraph -AccessToken $token -Scopes "User.ReadWrite.All"
Remove-MgUserMessage -UserId $email -MessageId $item.id
But then I get this error:
Connect-MgGraph : Parameter set cannot be resolved using the specified named parameters.
At D:\Scripts\GraphAPITest2.ps1:159 char:1
+ Connect-MgGraph -AccessToken $token -Scopes "User.ReadWrite.All"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Connect-MgGraph], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.Graph.PowerShell.Authentication.Cmdlets.ConnectMgGraph
Is not allowed to combine the -AccessToken and the -Scopes parameter?
I've been told that I've been given Mail.ReadWrite and ServiceMessageViewpoint.Write privileges.
When using a token, is it supposed to get all the scopes from the token?
Or do you still have to tell the PowerShell program that your intent is to do an delete or update, and not just a read?
I've also posted this question about "Variants", but no reply yet: What are "variants" in Azure permissions

If you connect by using a AccessToken there is no need to specify the scopes, as those are already defined in the token. After you did establish a connection you can verify which permissions the current session has with:
(get-mgcontext).Scopes
Once you authenticate to get the accessToken in the first step ensure that you have:
Scope = 'https://graph.microsoft.com/.default'
in the body to automatically claim all permissions available to that identity.

Related

Non-Interactive - Get-MgUser : Insufficient privileges to complete the operation

I followed https://www.christianfrohn.dk/2022/04/23/connect-to-microsoft-graph-with-powershell-using-a-certificate-and-an-azure-service-principal/ to connect to Microsoft Graph but I'm getting the following error.
Get-MgUser -Top 1
> Get-MgUser : Insufficient privileges to complete the operation.
> At line:1 char:1
> + Get-MgUser -Top 1
> + ~~~~~~~~~~~~~~~~~
> + CategoryInfo : InvalidOperation: ({ ConsistencyLe...ndProperty = }: <>f__AnonymousType62`9) [Get-MgUser
> _List1], RestException`1
> + FullyQualifiedErrorId : > Authorization_RequestDenied,Microsoft.Graph.PowerShell.Cmdlets.GetMgUser_List1
From what I can tell I need to consent to the permissions. I found numerous sources for how to do this for interactive sessions but nothing said how to do this for non-interactive sessions.
I tried adding -Scopes to the connection string but got this error
Connect-MgGraph -ClientID [snip] -TenantId [snip] -CertificateThumbprint [snip] -Scopes 'User.Read.All'
> Connect-MgGraph : Parameter set cannot be resolved using the specified named parameters.
> At line:1 char:1
> + Connect-MgGraph -ClientID 19cb80c5-b355-42bc-a892-e73d11f57ef4 -Tenan ...
> + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> + CategoryInfo : InvalidArgument: (:) [Connect-MgGraph], ParameterBindingException
> + FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.Graph.PowerShell.Authentication.Cmdlets.ConnectMgGraph
How do I do this?
EDIT
This is how I'm connecting
Connect-MgGraph -ClientId $clientId -TenantId $tenantId -CertificateThumbprint $thumbPrint
Welcome To Microsoft Graph!
API Permissions
Thanks
Your App Registration has the incorrect permissions. There are 2 types of permissions, delegated (aka scope), and application (aka role).
Reference: Permission types
For an "interactive" session, your app will be interacting on behalf of the user, therefore uses delegated permissions.
For a "non-interactive" session, your app will be acting as itself, so it needs application type permissions.
When connecting as an application ("non-interactive"), you also don't specify the -Scopes parameter
To identify the permissions needed to run a specific cmdlet of the microsoft.graph module you can use the find-mgGraphCommand cmdlet, e.g.:
(Find-MgGraphCommand -Command get-mguser).permissions
To identify which permissions are assigned to the current session you can use the get-mgcontext cmdlet, e.g.:
(get-mgcontext).scopes
If you run a interactive session you have to specify the scopes, e.g.:
Connect-MgGraph -Scopes user.read.all
To connect in the context of a service principal by using a certificate you can do:
#Get the certificate used as secret from the Windows certificate store
$cert = Get-ChildItem -Path 'Cert:\LocalMachine\MY' | ?{$_.thumbprint -eq $CertificateThumbprint}
#establish connection
connect-mggraph -certificate $cert -tenantid [tenantId] -clientId [clientId]
btw. clientId = objectId of the service principal

Powershell : Connect-partnercenter Error: ClientId is not a Guid

Here is my problem, I want to get the list of people with administrator role on O365 partner center while going through Azure Automation for scheduled task.
One of the first problems, is that access to the partner center is that you have to have the MFA activated on the account that does it. So I created an Azure application by following the information here: https://www.cyberdrain.com/connect-to-exchange-online-automated-when-mfa-is-enabled-using-the-secureapp-model/
The application has been created successfully, so I run the command given on the Microsoft site at the bottom (https://learn.microsoft.com/en-us/powershell/partnercenter/multi-factor-auth?view= partnercenterps-3.0):
$credential = Get-Credential
$refreshToken = '<refreshToken>'
Connect-PartnerCenter -ApplicationId 'xxxx-xxxx-xxxx-xxxx' -Credential $credential -RefreshToken $refreshToken
The problem is that when I run this command, this is the message I get:
Connect-PartnerCenter : Error: ClientId is not a Guid.
At line:8 char:1
+ Connect-PartnerCenter -ApplicationId $ApplicationId -Credential $cred ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Connect-PartnerCenter], MsalClientException
+ FullyQualifiedErrorId : Microsoft.Store.PartnerCenter.PowerShell.Commands.ConnectPartnerCenter
I have searched everywhere, I do not understand where this problem comes from.
Have some of you already encountered this problem or have another solution to get the list of admin people on the partner center?
Thank you

Google Text-to-Speech : Error could not auto authenticate

I'm using the google text to speech API in the powershell. I've created the project, enabled the api, created the key, when I tell it this
$cred = gcloud auth application-default print-access-token
$headers = #{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest -Method POST
-Headers $headers -ContentType: "application/json; charset=utf-8"
-InFile request.json `
-Uri "https://texttospeech.googleapis.com/v1/text:synthesize" | Select-Object -Expand Content
And this is after I set the environment, I get this error message
ERROR: (gcloud.auth.application-default.print-access-token) Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://cloud.google.com/docs/authentication/getting-started
Invoke-WebRequest : The remote server returned an error: (403) Forbidden.
At line:4 char:1
Invoke-WebRequest `
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebExc
eption
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
I have attempted to recreate the key thinking that was maybe the issue but I keep getting this error here no matter what I do, I am using this code to point to the key
$env:GOOGLE_APPLICATION_CREDENTIALS=C:\IVR2\IVR2-ba991f7cce6a.json
For an application, you would set the env variable GOOGLE_APPLICATION_CREDENTIALS which is the location of your service account json file.
It looks like you're using gcloud to get creds and including an authorization header. That should work too. Does your gcloud command return an error?

Is there a way to connect to New-CsOnlineSession using an oauth token?

I am looking for a way that I can run 'New-CsOnlineSession' from a web-app using an oauth token. The WebApp will be responsible for authenticating a user. This will use Microsoft Modern Authentication which will handle two factor authentication and consent.
I have registered an App in the Azure Portal and given the User Impersonation permission for Skype For Business Powershell Server Application.
How ever when I connect with a token that is obtained using the WebApp I get an error that the wrong audience is being used.
Below is the transcript from my powershell session. Once I have this working in powershell, the idea is that the WebApp will execute the powershell commands, so any way of doing this where PowerShell prompts for the credentials will not work.
PS C:\WINDOWS\system32> $token = ConvertTo-SecureString -String $oauthtoken -AsPlainText -Force
PS C:\WINDOWS\system32> $session = New-CsOnlineSession -OAuthAccessToken $token -Verbose
VERBOSE: OAuthAccessToken is provided.
VERBOSE: Determining domain to administer
VERBOSE: AdminDomain = 'mydomain.onmicrosoft.com'
VERBOSE: Discovering PowerShell endpoint URI
VERBOSE: TargetUri = 'https://admin2e.online.lync.com/OcsPowershellOAuth'
VERBOSE: AuthUri = 'https://login.windows.net/common/oauth2/authorize', ClientId = 7716031e-6f8b-45a4-b82b-922b1af0fbb4
VERBOSE: Validating authentication token.
New-CsOnlineSession : OAuthAccessToken has invalid audience https://teamsconfigapi-int.trafficmanager.net, expected https://admin2e.online.lync.com/OcsPowershellOAuth.
At line:1 char:12
+ $session = New-CsOnlineSession -OAuthAccessToken $token -Verbose
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,New-CsOnlineSession
Could you try setting the -OverrideAccessTokenResourceUri to the specified URL.

powershell returned an error:(403) WebException using New-pnpList

I had my PS script running the other day and created a new list with a single field with no issues. Was able to view the list in the Site Contents lib.
Today, it's not working. I tried running the PS code below and then resorted to running the new-pnplist code at the command line...got the same error which is shown below.
I'm using the Global admin account. Using version 3.13.19 SharePointPNPPowerShellOnline. Executed the commands from Powershell ISE which is what I did the other day when it worked. And, I was able to connect successfully using the Connect-sposervice command.
Error:
new-pnplist -Template GenericList -Title 'TestPNP2'
new-pnplist : The remote server returned an error: (403) Forbidden.
At line:1 char:1
+ new-pnplist -Template GenericList -Title $ListName
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : WriteError: (:) [New-PnPList], WebException
+ FullyQualifiedErrorId : EXCEPTION,SharePointPnP.PowerShell.Commands.Lists.NewList
Code:
$TargetListURL="https://<my sharepoint.com>/sites/CKCDemo"
$ListName="TESTPNP2"
Connect-PnPOnline -url $TargetListURL -CurrentCredentials
New-PnPList -Template GenericList -Title $ListName
Add-PnPField -List $ListName -DisplayName "MyTEST" -InternalName "MyTEST" -Type Text -AddToDefaultView
Get-PnPList`
Make sure you have enough permission to create a list in this site. You could try to go to the site directly, check whether you could create a list through ui.
Note: A global admin will not automatically have access to individual sites unless explicitly granted.