New-AzureADPolicy : Error occurred while executing NewPolicy in windows powershell - powershell

I am trying to follow the instructions on the Microsoft website (https://learn.microsoft.com/en-us/azure/active-directory/active-directory-configurable-token-lifetimes) to configure a custom token expiry policy.
However I am getting an incomprehensible error message. It does not appear to be a temporary error as I have tried it a few times over the last few days.
I have tried running Powershell as both normal and "as administrator", it makes no difference to the outcome.
PS C:\Users\sheakbar> New-AzureADPolicy -Definition #(‘{“TokenLifetimePolicy”:{“Version”:1,”MaxInactiveTime”:”14.00:00:00″,”MaxAgeSing
leFactor”:”90.00:00:00″,”MaxAgeMultiFactor”:”90.00:00:00″,”MaxAgeSessionSingleFactor”:”until-revoked”,”MaxAgeSessionMultiFactor”:”unti
l-revoked”}}’) -DisplayName “OrganizationDefaultPolicyScenario” -IsOrganizationDefault $true -Type “TokenLifetimePolicy”
New-AzureADPolicy : Error occurred while executing NewPolicy
Code: Authorization_RequestDenied
Message: Insufficient privileges to complete the operation.
InnerError:
RequestId: 4c0f01de-96b4-4483-8a19-43b411149880
DateTimeStamp: Thu, 07 Jun 2018 04:28:08 GMT
HttpStatusCode: Forbidden
HttpStatusDescription: Forbidden
HttpResponseStatus: Completed
At line:1 char:1
+ New-AzureADPolicy -Definition #(‘{“TokenLifetimePolicy”:{“Version”:1, ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [New-AzureADPolicy], ApiException
+ FullyQualifiedErrorId : Microsoft.Open.MSGraphBeta.Client.ApiException,Microsoft.Open.MSGraphBeta.PowerShell.NewPolicy

According to the error message, it seems like your account is not a global admin in your tenant and doesn't enough permissions to excute this powershell command.
Solution:
Run the Connect command Connect-AzureAD to sign in to your Azure AD admin account.

If we use global administrator(xxx.onmicrosoft.com) account to connect-AzureAD.
Then we could New-AzureADPolicy, and I test it on my side with following command
New-AzureADPolicy -Definition #('{"TokenLifetimePolicy":{"Version":1,"MaxInactiveTime":"14.00:00:00","MaxAgeSingleFactor":"90.00:00:00","MaxAgeMultiFactor":"90.00:00:00","MaxAgeSessionSingleFactor":"until-revoked","MaxAgeSessionMultiFactor":"until-revoked"}}') -DisplayName "OrganizationDefaultPolicyScenario" -IsOrganizationDefault $true -Type "TokenLifetimePolicy"

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

Getting a 'WS trust response'-error when executing Connect-PnPOnline in Powershell

Since I updated the Powershell Pnp-module to the latest version (1.10.0) I get the following error when trying to connect to PnpOnline:
PS C:\Users\Admin> Connect-PnPOnline -Url "https://testscholengroepbrussel.sharepoint.com/sites/so-kae"
Connect-PnPOnline : There was an error parsing WS-Trust response from the endpoint. This may occur if there is an issue with your ADFS configuration. See https://aka.ms/msal-net-iwa-troubleshooting for more details. Error Message: Federated service at https://autologon.microsoftazuread-sso.com/testscholengroepbrussel.onmicrosoft.com/winauth/trust/2005/usernamemixed?client-r
equest-id=65f9e4ff-ffc5-4286-8c97-d58fd2323ab1 returned error: Authentication Failure
At line:1 char:1
Connect-PnPOnline -Url "https://testscholengroepbrussel.sharepoint.co ...
+ CategoryInfo : NotSpecified: (:) [Connect-PnPOnline], MsalClientException
+ FullyQualifiedErrorId : Microsoft.Identity.Client.MsalClientException,PnP.PowerShell.Co
mmands.Base.ConnectOnline
There is no ADFS configured on the tenant, nor any other SSO-configuration made. I do not have the problem on another tenant ...
There's almost no info available on this problem, can anyone help?
Thx,
David

Error connecting to Exchange 2019 EWS with PowerShell

I migrated from Exchange 2016 to 2019. I have a PowerShell script I use to connect into exchange using EWS to access the inbox of a user. It keeps failing on connect. I tried to see if there is anything different from 2016 to 2019 but am coming up empty. Here is the code I was using to connect to 2016
Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll"
$User_Domain = "domain"
$Password = "user_pass"
$EWS = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService -ArgumentList "Exchange2013"
$EWS.Url = "https://mail19.server.com/EWS/Exchange.asmx"
$Username = "username"
$EWS.Credentials = New-Object System.Net.NetworkCredential -ArgumentList $Username, $Password, $User_Domain
$inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($EWS,[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox)
When I run the last line I get this error:
Exception calling "Bind" with "2" argument(s): "The request failed. The underlying connection was closed: An unexpected error occurred on a send."
At line:1 char:1
+ $inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($EWS,[Mic ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ServiceRequestException
This worked fine on my old 2016 exchange server. I am wondering if there is something on exchange I need to tweak or if the code needs tweaked to be able to work with exchange 2019. I am able to access the EWS url and log in with the username/password.
Ok after scouring the internet it seems to be an issue with Exchange 2019 enforcing TLS1.2. I added the following line to the powershell script and the error goes away
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12;
Hopefully that helps someone else

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.

How to make normal user remote to Windows 2016 by powershell?

I'm trying following powershell script to remowe to windows 2016.
$password = ConvertTo-SecureString "Password" -AsPlainText -Force
$cred= New-Object System.Management.Automation.PSCredential ("username", $password )
enter-pssession -computername 192.168.xxx.xxx -credential $cred
When login with user that has "Adminstrators" permission, it works just fine, but when login with user that only has "Users" permission, it gets access is denied error.
So, What should I do to make "Users" to login with powershell?
OK, I follow the guide below
https://www.sevecek.com/EnglishPages/Lists/Posts/Post.aspx?List=f6e49214-a43d-4fa5-9537-fb46eabe0cb8&ID=4&Web=6dbd0194-ad16-4838-ad08-7f33e3009473
And I can remote Windows Server 2016 with normal user.
But when I tried following script, the exception happens again.
[192.168.XXX.XXX]: PS C:\Users\TestUser\Documents> ([ADSI] "WinNT://localhost/TestUser,user").ChangePassword("#EDC4rfv", "1qaz#WSX")
And the error message is
Exception calling "ChangePassword" with "2" argument(s): "Access is denied.
"
At line:1 char:1
+ ([ADSI] "WinNT://localhost/TestUser,user").ChangePassword("#EDC4rfv", " ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : CatchFromBaseAdapterMethodInvokeTI
Does that mean even normal user can remote to Windows Server 2016, they still can't run commands?
To use PowerShell remoting(default endpoint "Microsoft.PowerShell"), the user should be part of Administrators group in remote machine.
You can tackle this by creating an Endpoint and giving the normal user permission to access it on the remote machine.
More about it is in below link.
https://blogs.technet.microsoft.com/heyscriptingguy/2014/03/31/introduction-to-powershell-endpoints/