Getting certificate details of an Intune managed device via Device ID - azure

I'm new to Intune and a N00B at PowerShell.. Currently trying to get the Certificate info of a device managed by Intune by using the device ID. Relevent documentation has been hard to find..
My question is, how do I display info about a Device certificate and see info such as SubjectName, OrderNumber and more using PowerShell with a deviceID?
Steps taken so far:
Connected with "Connect-MgGraph" successfully
Get-MgDevice -DeviceId 'xxxxxxxxx' successfully
???
SCEP profile is setup and works as intended towards the PKI.The devices are getting certs and are able to connect to 802.1x

Install and import Microsoft.Graph.Intune module using below commands:
Install-Module -Name Microsoft.Graph.Intune
Import-Module -Name Microsoft.Graph.Intune
Try executing the below script to get the intune managed devices certificate information as shown:
connect-Mggraph
$device = Get-IntuneManagedDevice -deviceId "<DeviceID>"
$certificates = Get-IntuneManagedDeviceCertificate -DeviceId $device | select thumbprint, device //Select for the required fields
Connected successfully:
Search for Intune in Azure Portal and it will redirect you to below page.
Check for the commands in Microsoft Intune using below command:
Get-Command -Module Microsoft.Graph.Intune
Reference

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.

Powershell - Connecting to SQL Server using Connect-AzAccount (With MFA)

We have a SQL Server set up (created by me, with my account as the admin account), and using Management Studio, I can access the database just fine. I'm now trying to achieve the same thing through Powershell.I have created my own user using:
CREATE USER [<my ccount>] FROM EXTERNAL PROVIDER
I start by connecting using MFA (and signing in using the pop-up window/MFA):
Connect-AzAccount -SubscriptionId $subscriptionID
This works fine, and returns the expected values of the subscription specified, and my Azure AD Login as account. I can access my KeyVault and pull secrets from there.
I now would like to connect to my SQL Server using the credentials I'm already signed in with within the PowerShell session, and that's where I get stuck.
I tried a ConnectionString including Authentication=Active Directory Integrated, but that throws an error Exception calling "Open" with "0" argument(s): "One or more errors occurred.".
I then tried using a connection string like this: Server=tcp:<server>.database.windows.net,1433;Initial Catalog=<database>;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30, and adding an AccessToken using SqlConn.AccessToken = $(Get-AzAccessToken -ResourceUrl "Https://database.windows.net/").
However, when I then try to Open the connection, I get the error: "Login failed for user '<token-identified principal>'."
Googling led to several SO articles, but none of those use Connect-AzAccount, but the (what I believe to be outdated) Az Account (I.e. Connecting to SQL Server using Powershell with Azure AD MFA).
Other examples I found all add UID and Password, which should not be needed considering I authenticated already.
Is there a way to use the existing Connect-AzAccount session to authenticate against my Azure SQL Server, and if so, what format should the ConnectionString have? I have a feeling I'm very close to a solution, but just cannot seem to actually achieve the opening of the connection.
Thanks in advance.
After reading more and more, I finally stumbled across this thread. #golfalot's answer was exactly what I needed.
So the proper code to initialize the connection is:
# Sign in to Azure
Connect-AzAccount -SubscriptionID $subscriptionID
$connectionString = "Server=<server>.database.windows.net;Initial Catalog=<database>;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30"
$accessToken = (Get-AzAccessToken -ResourceUrl https://database.windows.net).Token
$sqlConn = New-Object System.Data.SqlClient.SqlConnection
$sqlConn.ConnectionString = $connectionString
$sqlConn.AccessToken = $accessToken
$sqlConn.Open()

Unable to Access SharePoint using PowerShell

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

Trying to connect via PowerShell to Azure with new AZ Module

I'm desperate here with Powershell and Azure.
I use PowerShell 7.0.1 and AZ 4.1.0.
When I try to connect (by the way, as global admin via 'Connect-AzAccount'), I get this prompt every time: "WARNING: To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code xxxxxxxxx to authenticate."
Of course I do that and then I get this error message every time:
Connect-AzAccount: xxxxxxxxxxxxx: Device authentication is required.
Trace ID: xxxxxxxxxxxxxxxxxxxxxxxxx
Correlation ID: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Timestamp: 2020-05-20 09:12:18Z: Response status code does not indicate success: 401 (Unauthorized).
Does anyone have an idea why this does not work? I have also tried it temporarily without MFA, with the same result.
As Allen pointed, the right thing to do in this case is to engage the ActiveDirectory authentication team.
Meanwhile, can you try the preview of the new authentication experience here.
This uses a vastly updated authentication experience, and may unblock you while we work out the underlying issue.
Use the below script to install Az.Accounts 2.0.1-preview module.
Install-Module -Name Az.Accounts -AllowPrerelease
For more details, you could refer to this issue.
I have installed Az.Accounts 2.0.1-preview, but now a different error message appears. After connecting all seams working fine, but after calling a function it comes to an error again:
PS> Connect-AzAccount -Subscription 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
WARNING: Attempting to launch a browser for authorization code login.
WARNING: We have launched a browser for you to login. For the old experience with device code flow, please run 'Connect-AzAccount -UseDeviceAuthentication'.
WARNING: Unable to acquire token for tenant 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy'
Account SubscriptionName TenantId Environment
------- ---------------- -------- -----------
michael.kristen#inhouse.wko.at INH-Subscription xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx AzureCloud
PS> Get-AzDefault
Get-AzDefault: Your Azure credentials have not been set up or have expired, please run Connect-AzAccount to set up your Azure credentials.

Why does getting a certificate from Azure Key Vault require it to be stored as a secret?

Blogs like the following
https://blogs.technet.microsoft.com/neales/2017/06/26/getting-a-private-certificate-from-key-vault/
Seem to retrive the secret? Does it not matter if it's "stored" as a certificate or not?
It depends on what you are planning to do with the certificate. You could update your question with details about the expected workflow you want to support.
But basically a certificate can be stored as a file. You can see more details (C#) to get inspired on how to do that after the certificate is loaded into a variable.
Exporting a Certificate as BASE-64 encoded .cer
Update
Security considerations to take into account. If you see the certificate stored in the azure key vault as a secret and you want to limit the access to it, then you have to consider how your PowerShell scripts will store the needed credentials for authenticate against the KeyVault.
If you plan on running the script unattended / scheduled without user interaction, you will have to store some kind of credentials on the machine that needs to run the script. BetterCredentials is a great PowerShell native module for storing credentials on the local machine.
I would recommend that you create an Azure Service Principal (App Registration / Registered App), that will get only enough permissions to get the certificate from the KeyVault. The created Service Principal details should then be stored locally on the machine and you should load those credentials first and use them for connecting to the KeyVault.
Example code that should be capable of loading a Service Principal details from the BetterCredentials and sign into Azure:
BetterCredentials\Get-Credential -UserName <application ID> -Store
$azureTenantId = <tenant ID>
$Cred = BetterCredentials\Get-Credential -UserName <application ID>
Add-AzureRmAccount -Credential $Cred -TenantId $azureTenantId -ServicePrincipal

Resources