When working with the Microsoft Graph API or introducing the API to colleagues I often get asked about the steps required to obtain an access token for the API with PowerShell. Out in the wild, I’ve spotted many different ways and lots of implementations still relying on the ADAL (Active Directory Authentication Library) despite the fact that this client library is superseded by MSAL (Microsoft Authentication Library). So let’s talk about acquiring access token “in stile” with the most simple method available.
Why do we need an access token? # When talking about the Microsoft Graph API an access token fulfills two roles, first: prove authentication (proof of identity) second prove authorization (permissions). Each request needs to submit a request-header that contains the access token.
For an API it’s crucial to validate the authentication and authorization for every request. Otherwise, requests could be made to resources the actor has no access to.
What’s inside the access token # You did probably stumble over the terms “bearer authentication” or “bearer token” these describe a mechanism within the OAuth 2.0 Authorization framework to authenticate requests with access tokens. Tokens are issued by the authorization server (Azure AD) and contain a server-generated string in the format of a JSON Web Token (JWT) with the following information (the list is not exhaustive and truncated to only contain the most interesting parts):
While doing some Android Enterprise enrollment tests for corporate-owned devices with work profiles I stumbled over the following issue after signing-in with the work account: “Page not found”.
The solution is fairly simple, just double check that your user does not have the device enrollment manager role assigned, which can be found under the device enrollment pane: The docs tell us:
If you’re enrolling Android Enterprise personally-owned work profile or corporate-owned work profile devices by using a DEM account, there is a limit of 10 devices that can be enrolled per account. Microsoft Docs
In my case, I wasn’t exceeding that limit because it was the first enrollment with that account so I’m not sure if the docs are accurate.
Updated 21.12.2020:
I already opened an issue on GitHub about the doc contents.
@nicolonsky Good question. Using a DEM account isn’t available to enroll COPE devices. We fixed the article. The changes should be live later today. Thanks for bringing this to our attention.
Hope this helps.
I like to have a linux machine for some lab stuff which I can access from multiple machines prefereably over SSH. Because Windows 10 ships with an integrated SSH client and Windows Terminal looks just awesome I wanted to use Windows Terminal to access my linux machine running on Azure over SSH. Today I’d like to show you my setup.
Generate a Key Pair # ssh-keygen Generating public/private rsa key pair. Enter file in which to save the key (C:\Users\NicolaSuter/.ssh/id_rsa): Created directory 'C:\Users\NicolaSuter/.ssh'. Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in C:\Users\NicolaSuter/.ssh/id_rsa. Your public key has been saved in C:\Users\NicolaSuter/.ssh/id_rsa.pub. Add SSH config file # C:\Users\%USERNAME%\.ssh\config
Host horus Hostname horus.nicolonsky.ch Port 22 User azureuser IdentityFile ~/.ssh/id_rsa Test the SSH connection # ssh horus
Windows Terminal Configuration # Create a new GUID with Powershell and the command: (New-Guid).Guid
{ "guid": "{67d39a21-70ff-4bdd-af09-fd68b29c1716}", "name": "Horus", "commandline": "ssh horus", "hidden": false, "icon": "https://image.flaticon.com/icons/png/512/119/119423.png" }, Sync Windows Terminal Settings with OneDrive # We can setup a symlink to use the Windows Terminal Config stored in OneDrive:
When involved in new projects I often find a bunch of old profiles in the Microsoft Endpoint Management Console. Before going ahead with a new implementation it’s the best time to clean-up all the leftovers from past ramblings.
How to identify stale profiles # If one or multiple statements are met for a profile it is very likely to be a stale profile:
No assignments, assignments to a group without members “Test” included within the profile name or description Last modified points back in time for more than a year No devices reported success/failure status for the given profile type What to do with stale profiles # So let’s be brave and delete them. But Intune doesn’t offer any [CTRL] + [Z] or recycle bin possibilities so we might want to have some kind of archive, just in case?
Let’s agree that we:
Check the points from the list above Ask our colleagues if they know something about the profiles and their usage Take a backup deleting them afterward is a reasonable action which is probably beneficial for everyone.
Recently I got a DM on Twitter with a question about how to export and import Endpoint Security profiles with Microsoft Graph. Besides a technical answer which might be of interest for you, I’d like to show you the workflow I used to give a proper reply.
Original question:
Hi @nicolonsky, I was advised on the MS Elite Partner focus groups team (MEM Automation) to reach out to you regarding my question about export/import policies from Endpoint Security in Intune. I’ve been able to export the Disk Encryption policy (via graph explorer), but haven’t been able to find the correct format to use to upload/import it. I was hoping that you would be able to advise on how to go about achieving this.
Workflow # Discover request URL’s and payload # To discover the request URLs and payloads I used the methodology I explained in the this post a while ago. Basically, I tracked the network activity and used a filter to only include requests made to the Graph API while doing the following activities:
I recently bought a Surface Pro 7 with an Intel Core i7 and 256 GB SSD and it was a quite good deal. I’m using it primarily for my studies in computer sciences which involves lots of development with Java, Python, C, Linux and so on. Furthermore, I’m using it to write blog posts for this blog.
One thing which annoyed me since day 1 was the fan going absolutely crazy when plugged to AC power. Having only OneNote open and a couple of browser tabs and maybe teams the noise was way too loud and even heard by other participants in meetings.
On Reddit I found a hint to a setting which indeed solved my solution.
We need to adjust the “max. processor power state” setting which is not visible by default on surface devices. To show the setting add this reg key with PowerShell:
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Power\PowerSettings\54533251-82be-4824-96c1-47b60b740d00\bc5038f7-23e0-4960-96da-33abaf5935ec" -Name Attributes -Value 2 Afterwards, we can change the “max. processor power state” setting within the power settings in the control panel:
Hope this helps you as well to enjoy your Surface Pro 7 with a much quieter fan. 🐱💻
Too lazy to sign your PowerShell scripts? Yes of course it provides security benefits but performing the steps manually can be easily forgotten and re-signing needs to happen after every script change. Because I like CI/CD topics and have not found a solution on the internet I decided to build a solution based on Azure capabilities. Furthermore, I wanted a solution which does not require to hand out the code signing certificate to the respective script author which can be useful if you have a bunch of people writing PowerShell scripts.
From a personal perspective, I would also recommend signing scripts you hand over to customers to ensure the integrity of the scripts because as soon as the script gets changed the signature is invalid.
You can find more general recommendations about script signing in the PowerShell docs.
Solution overview # The key vault will store the code signing certificate with an access policy that allows access from the Azure DevOps pipeline.
The pipeline consists of the following steps:
Import code signing certificate The certificate is supplied as secret in a variable group which is linked to the key vault Access to the key vault is granted with a service connection (service principal) Sign PowerShell scripts which contain a “magic token” All *.ps1 within the attached repository will be enumerated To control which scripts will be signed only those with the “magic token” get processed The “magic token” gets removed before signing the script Publish signed PowerShell scripts as pipeline artifacts To make them available for download
While looking into the new Microsoft Defender Antivirus report available in MEM (Intune) I discovered some machines which did not report any recent Defender antimalware scans, despite configured via configuration profile. Of course, AV scans are kinda old-fashioned against rapidly evolving threats but a regular quick scan won’t hurt anyone. Instead of having a look at every single machine affected, I decided to try out the new proactive remediations feature which went globally available last week and let endpoint analytics do the detection and remediation work for me. As a reference, I used the Tutorial: Proactive remediations from Microsoft which covers the process quite well.
PowerShell scrips # For Endpoint analytics / Proactive remediations we need two PowerShell scripts. The first script is used as a detection script and determines whether remediation is necessary based on the exit code. Exit code 0 indicates a healthy status and exit code 1 indicates remediation necessary. Remediation occurs with a second PowerShell script.
To detect the most recent Defender scan I used the Windows Eventlog. Event ID’s are documented here.
Detection script # Remediation script # The remediation script is just about a one-liner to trigger a quick scan. You can extend this based on your requirements and respective to your Intune settings. E.g. triggering a signature update for a scan or adding additional steps.
You always wanted to automate a specific action within Intune / the Microsoft Endpoint Manager Portal (MEM) but were afraid of the complexity? The Microsoft Graph API docs deliver you more questions instead of answers? Automating tasks within the MEM portal could be very easy, couldn’t it? I promise it will be much simpler with this magician trick.
Microsoft Endpoint Manager Portal # The MEM Portal UI relies on the Microsoft Graph API. This means that the UI where you create new settings and policies and the Intune backend are encapsulated with different layers. Communication between the UI and the backend happens with the Microsoft Graph API. With the developer tools we can trace network traffic and discover the request URLs and request body payload which are required to interact with the API.
{: .align-center}
Example about how to capture URLs and build a PowerShell script # Original request body:
When using device code authentication for PowerShell modules with conditional access you might receive prompts like: “Access has been blocked by Conditional Access policies. The access policy does not allow token issuance” or “AADSTS50097: Device authentication is required”. But what’s the reason for this error and is there a solution available?
Examples from the field # Device code flow is quite a convenient way to sign-in for an app within the web browser - at least if it works. If not you have to consider other options and that’s probably the reason why you’re reading this blog article.
Az PowerShell
Running the Az PowerShell module on PowerShell 7 uses device code flow to authenticate against your Azure tenant and might fail:
Connect-AzAccount: AADSTS50097: Device authentication is required. Timestamp: 2020-08-17 13:36:31Z: Response status code does not indicate success: 401 (Unauthorized). The sign-in to Azure is tied to the “Microsoft Azure Management” app that you can select within Conditional Access.
Microsoft Graph PowerShell
The same applies for the new Microsoft.Graph PowerShell modules - but here we receive a more detailed error message:
Connect-Graph: AADSTS53003: Access has been blocked by Conditional Access policies. The access policy does not allow token issuance. Timestamp: 2020-08-17 13:37:12Z The sign-in to the new Microsoft Graph Modules is tied to the “Microsoft Graph PowerShell (Preview)” app and some more apps I couldn’t determine.