How to get company domain name for user from azure ad - azure-active-directory

How to retrieve details which contains information of login user including domain for example let say domain\useralias from Azure AD for a user input? Note that domain names are there in onprem ad which were sync to Azure AD.

You can use the OnPremiseDistinguishedName extension property.
Example:-
foreach($line in Get-Content c:\users\myuser\users.txt) {
if($line -match $regex){
$onPremisesDistinguishedName = (Get-AzureADUserExtension -ObjectId $line).get_item("onPremisesDistinguishedName")
$domain = $onPremisesDistinguishedName.split(",")
$alias = $line.Split("#")
$sAMAccountName = ($domain[2]).Substring(3)
$sAMAccountName + "\" + $alias[0]
}
}

Related

Get expiration date of signing certificate(s) within a SAML metadata file

I have about 30 SAML configurations from various vendors, all are metadata files that reside on the internet (Azure AD, Auth0 and a couple other identity providers).
Is there a tool that exists to extract the expiration date from the signing cert in the metadata file? So I can keep track of all the expiration? Preferably a CLI.
For workaround you can use this powershell command to get the expiry time of siging certificate that is uploaded in Azure AD application.
Based on your requirements you can edit the code and pull the certificate from metafiles rather than directly from AzureAD application.
$expired = Get-AzureADApplication -All:$true | ForEach-Object {
$app = $_
#(
Get-AzureADApplicationKeyCredential -ObjectId $_.ObjectId
$CustomKeyIdentifier = (Get-AzureADApplicationKeyCredential -ObjectId $_.ObjectID).CustomKeyIdentifier
)| Where-Object {
$_.EndDate }| ForEach-Object {
$id = "Not set"
if($CustomKeyIdentifier) {
$id = [System.Convert]::ToBase64String($CustomKeyIdentifier)
}
[PSCustomObject] #{
App = $app.DisplayName
ObjectID = $app.ObjectId
AppId = $app.AppId
Type = $_.GetType().name
KeyIdentifier = $id
EndDate = $_.EndDate
}
}
}
$expired | Export-CSV 'C:\test.csv
Reference : How to retrieve thumbprint expiry date of enterprises application in azuread

Exporting all the attributes from Azure AD B2C into a csv

I'm trying to export AAD users from ADB2C to a csv file. I'm able to achieve this using the graph API "graph.windows.net" and some filter conditions. But with this approach, I can only get a limit of 999 records per response and I need to get the next link to do another API call and so on...
This process is taking a long time to fetch the AAD users. Hence I tried using Power shell scripts i.e using Get-AzureADUser, using this approach I was able to get all the users within a short duration. But the issue in this approach I'm not able to get all the attributes that I get via the rest call (i.e the attribute is userIdentites).
The reason I'm looking for userIdentites is, that I can filter out the users with social logins like gmail.com or facebook.com
How can I achieve this using PowerShell scripts? or using CLI or Python?
A sample response from the Graph API -
Powershell script to get the same attributes, but I'm getting blank userIdentites, which is wrong. Expected is few users are to get social logins as shows in Graph API Response
For($i=$index; $i -lt $regexArray.Length; $i++){
$regexArray[$i] | Out-File $tempLogFile -NoNewline
$blobFileName = $fileName + $i + ".csv"
Write-Output ("Exporting Users Information in a CSV File for Surname with Regex : " + $regexArray[$i])
Get-AzureADUser -All $true | where-Object { $_.Surname -cmatch $regexArray[$i]} |
select otherMails,DisplayName,userIdentites,UserPrincipalName,Department | Export-Csv $tempfilepath -NoTypeInformation
Set-AzureStorageBlobContent -Context $context -Container $container -File $tempfilepath -Blob $blobFileName -Force
Write-Output ("Exported File Name : " + $blobFileName)
Set-AzureStorageBlobContent -Context $context -Container $container -File $tempLogFile -Blob $logFile -Force
Write-Output ("Exporting completed for Surname with Regex : " + $regexArray[$i])
}
public static async Task ListUsers(GraphServiceClient graphClient)
{
Console.WriteLine("Getting list of users...");
try
{
// Get all users
var users = await graphClient.Users
.Request()
.Select(e => new
{
e.DisplayName,
e.Id,
e.Identities
})
.GetAsync();
// Iterate over all the users in the directory
var pageIterator = PageIterator<User>
.CreatePageIterator(
graphClient,
users,
// Callback executed for each user in the collection
(user) =>
{
Console.WriteLine(JsonSerializer.Serialize(user));
return true;
},
// Used to configure subsequent page requests
(req) =>
{
Console.WriteLine($"Reading next page of users...");
return req;
}
);
await pageIterator.IterateAsync();
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex.Message);
Console.ResetColor();
}
}
https://learn.microsoft.com/en-us/samples/azure-samples/ms-identity-dotnetcore-b2c-account-management/manage-b2c-users-dotnet-core-ms-graph/

Retrieve photos on Azure

I have a task to do on Azure.
On Azure, I need to get photos with a link like this :
https://picture.blob.core.windows.net/datapicture
I was given this document.
https://learn.microsoft.com/en-us/powershell/module/azure.storage/get-azurestorageblobcontent?view=azurermps-6.13.0
The goal is to make a powershell script that allows you to retrieve photos in this path with Azure.
I don't have a key to login but a login user and password.
My connection model is, I think :
Login-AzureRmAccount
$SourceResourceGroupName = "...";
$SourceServerName = "...";
$Database = "...";
$ServerInstance = "...";
$Username = "...";
$Password = "..."
$con.ConnectionString = "Server=$ServerInstance;
uid=$Username;
pwd=$Password;
Database=$Database;
Integrated Security=False;"
$con.Open();
Thank you in advance for helping me.
Seems that you are trying to download file from Azure Blob Storage. It is not working like a database.
Just as silent explained in comment, Azure Storage supports symmetric key and Azure AD authentication. Or, you can set your file to public in which way it can be accessed directly.
You used Login-AzureRmAccount command. So, you should be able to download a blob as following:
$ResourceGroup = "Jack"
$StorageAccount = "storagetest789"
$Container = "function"
Set-AzureRmCurrentStorageAccount -ResourceGroupName $ResourceGroup -Name $StorageAccount
Get-AzureStorageBlobContent -Container $Container -Blob "User1.txt" -Destination 'D:\'
Update
A normal storage blob URL should look like the following: https://{storage_account_name}.blob.core.windows.net/{container_name}/{blob_name}
So, you may get $StorageAccount, $Container and $Blob as following:
$UserName = '.......';
$Password = '.........';
$Secret = ConvertTo-SecureString -String $Password -AsPlainText -Force;
$PsCred = New-Object System.Management.Automation.PSCredential($UserName, $Secret);
Login-AzureRmAccount -Credential $PsCred;
$ResourceGroup = '';
$URL = 'https://{storage_account_name}.blob.core.windows.net/{container_name}/{blob_name}';
$StorageAccount = $URL.Substring('https://'.Length,$URL.IndexOf(".")-'https://'.Length);
$Path = $URL.Substring($URL.IndexOf('.blob.core.windows.net/')+'.blob.core.windows.net/'.Length);
$Container = $Path.Substring(0,$Path.IndexOf('/'));
$Blob = $Path.Substring($Container.Length+1);
Set-AzCurrentStorageAccount -ResourceGroupName $ResourceGroup -Name $StorageAccount;
Get-AzStorageBlobContent -Container $Container -Blob $Blob -Destination 'D:\';

Azure app registration returns error code AADSTS70001

I have created a provisioning mechanism not unlike this here:
group provisioning mechanism
I have successfully implemented the whole workflow on my developer tenant. Now our productive environment, I always receive this error:
[Error]Invoke - RestMethod: {
"error": "unauthorized_client",
"error_description": "AADSTS70001: Application 'ffffffff-...' is disabled.\r\nTrace ID: ffffffff-180f-4bc4-8087-867633c83e00\r\nCorrelation ID: ffffffff-2e5d-481d-adee-f068dbebaab1\r\nTimestamp: 2018-10-29 09:06:59Z",
"error_codes": [70001],
"timestamp": "2018-10-29 09:06:59Z",
"trace_id": "ffffffff-180f-4bc4-8087-867633c83e00",
"correlation_id": "ffffffff-2e5d-481d-adee-f068dbebaab1"
}
This is my code, that should do the authentication:
function Initialize-Authorization {
param
(
[string]
$ResourceURL = 'https://graph.microsoft.com',
[string]
[parameter(Mandatory)]
$TenantID,
[string]
[Parameter(Mandatory)]
$ClientKey,
[string]
[Parameter(Mandatory)]
$AppID
)
$Authority = "https://login.microsoftonline.com/$TenantID/oauth2/token"
Write-Output "auth: $Authority"
[Reflection.Assembly]::LoadWithPartialName("System.Web") | Out-Null
$EncodedKey = [System.Web.HttpUtility]::UrlEncode($ClientKey)
$body = "grant_type=client_credentials&client_id=$AppID&client_secret=$EncodedKey&resource=$ResourceUrl"
Write-Output "body: $body"
# Request a Token from the graph api
$result = Invoke-RestMethod -Method Post ` #`
-Uri $Authority ` #`
-ContentType 'application/x-www-form-urlencoded' ` #`
-Body $body
$script:APIHeader = #{'Authorization' = "Bearer $($result.access_token)" }
}
I already tried generating new keys but I'm stuck. How can the app registration be disabled?
Can someone guide me in the right direction with this?
It appears the ServicePrincipal object for your app, in your production tenant, has been disabled. The ServicePrincipal object is represented under "Enterprise apps" in the Azure portal.
In the production tenant, navigate to the Azure portal > Azure AD > Enterprise applications. Search for your app (if it doesn't show up initially, make sure you've selected "All Applications", under "Application Type"). Choose the app, and in the new blade, choose "Properties", on the left.
If "Enabled for users to sign in?" is set to "No", then the app is disabled in that tenant. Setting it to "Yes" will enable it.
Apps don't generally get disabled automatically, so it will probably be a good idea for you to understand why this was disabled, and ensure everyone is clear on what the requirements are.

How to know permissions to other apis of my app

How to know the permissions of my azure ad app have for other APIs, such as Microsoft Grahp API .
In portal , i could check that in the [API Access]-->[Required permissions] , but how do i check that with powershell , i used
Get-AzureRmADApplication -ObjectId ,
Get-AzureRmADApplication -ObjectId xxxxx | fl *
But little attributes returned and AppPermissions is null , but with fiddle , i notice it use below request :
GET https://graph.windows.net/mytenant/applications/id?api-version=1.6 HTTP/1.1
And i could find a lot of attributes of that app ,which one shows the permission of the app and how do i get that in powershell ?
You could try the Azure Active Directory PowerShell Version 2 , the use command like :
$app = Get-AzureADApplication -Filter "appId eq '$appId'" | fl *
to get the RequiredResourceAccess claim ,that is the collection that is shown under "permissions to other applications" in the azure ad classic portal and "Required permissions" in new portal .
In addition , PowerShell essentially wraps the API's and just presents them to you in a simplified interface. If you don't find a command to do what you want you can always using PowerShell to invoke the Graph API directly. Please refer to below article for how to call Azure Active Directory Graph Api from Powershell :
https://blogs.technet.microsoft.com/paulomarques/2016/03/21/working-with-azure-active-directory-graph-api-from-powershell/
And here is a test code sample :
PS C:\Users\v-nany> $header = #{
>> 'Content-Type'='application\json'
>> 'Authorization'=$token.CreateAuthorizationHeader()
>> }
PS C:\Users\v-nany> $uriSAs = "https://graph.windows.net/xxxxxxx/applications/xxxxxx?api-version=1.6 "
PS C:\Users\v-nany> $appInfo = (Invoke-RestMethod -Uri $uriSAs –Headers $header –Method Get –Verbose)
PS C:\Users\v-nany> $appInfo.requiredResourceAccess
You will get resourceAppId represents the resource , and related resourceAccess which is a scope list.

Resources