<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tanmoy Naiya on Medium]]></title>
        <description><![CDATA[Stories by Tanmoy Naiya on Medium]]></description>
        <link>https://medium.com/@tanmoy6292?source=rss-ac93a5188433------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ZSVd4hBU3g7esfB5</url>
            <title>Stories by Tanmoy Naiya on Medium</title>
            <link>https://medium.com/@tanmoy6292?source=rss-ac93a5188433------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 05:29:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tanmoy6292/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Add permissions to Managed Identity resources through Graph API]]></title>
            <link>https://medium.com/@tanmoy6292/add-permissions-to-managed-identity-resources-through-graph-api-e8596253b62a?source=rss-ac93a5188433------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8596253b62a</guid>
            <category><![CDATA[azure-managed-identities]]></category>
            <category><![CDATA[managed-identity]]></category>
            <category><![CDATA[microsoft-graph-api]]></category>
            <dc:creator><![CDATA[Tanmoy Naiya]]></dc:creator>
            <pubDate>Wed, 18 Jun 2025 14:30:12 GMT</pubDate>
            <atom:updated>2025-06-18T14:37:10.737Z</atom:updated>
            <content:encoded><![CDATA[<p>It is easy to add permissions (Application/delegated) to you service principal as you can do it easily from the user interface from the azure portal if you dont want to do it programatically, on the other hand it is not that easy to add permission to your enyterprise applications or managed identity resources as there is no way to achive this from user interface and only way can do it programmatically. There are of-course many wato to achive this but today we will be discussing how we can do achieve this using Graph API( application permission) in PowerShell.</p><h4>1. Get the Service Principal for the first party Microsoft application</h4><p>You need the servicePrincipal object for Microsoft Graph (App ID: 00000003-0000-0000-c000-000000000000). Each organization has this application but with the diffrent object ID and we need to find out the object id of that application.</p><p>In this exapmle we want to add Graph permission that is why we are looking for Graph application, if you are trying to add permission for other applications like exchange online or Sharepoint online then you have to search for that specific application. You can find all the Microsoft first party appid <a href="https://learn.microsoft.com/en-us/power-platform/admin/apps-to-allow">here</a></p><pre>GET https://graph.microsoft.com/v1.0/servicePrincipals?$filter=appId eq &#39;00000003-0000-0000-c000-000000000000&#39;</pre><h4>2. find out the permission id you want to add to your application</h4><p>Once you get the object id from the step1 now you can find out what are the permission availble for you to assign it to your target application.</p><pre>GET https://graph.microsoft.com/v1.0/servicePrincipals/$appObjectId/approles</pre><p>after succesfull retrive you will be seeing data like below, where the <strong>value</strong> would be the permission you are looking for and the <strong>id</strong> would be the <strong>permission id</strong> for that particular permission, make a note of that permission id which is needed for the next step, also be careful while choosing the permission based on <strong>allowedMemberTypes</strong> depending on your requirement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*thK5iO5iqA-z-HWRbR8lPw.png" /></figure><h4>3. Assign the permission</h4><p>Now that you have all the details which you needed for assigning the permission. You can add the permission by calling below endpoint.<br>principalId: Your app&#39;s service principal ID<br>resourceId: Microsoft Graph&#39;s service principal ID<br>appRoleId: The ID of the permission you want to assign (e.g., User.Read.All)</p><pre>POST https://graph.microsoft.com/v1.0/servicePrincipals/{your-app-sp-id}/appRoleAssignments<br><br>Content-Type: application/json<br><br>{<br>  &quot;principalId&quot;: &quot;{your-app-sp-id}&quot;, # object id of your application<br>  &quot;resourceId&quot;: &quot;{graph-sp-id}&quot;, # object id of MS first party application from step 1<br>  &quot;appRoleId&quot;: &quot;{permission-id}&quot; # id of the permission from the step 2<br>}</pre><p>If everything goes well you can see the permission has been added to your application</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iXjc9S_4i_93o7QODfZ9bg.png" /></figure><h4>4. Required permission to perform above steps</h4><p>To execute these Graph API calls, your token must have:</p><p>AppRoleAssignment.ReadWrite.All<br>Application.Read.All<br>Directory.ReadWrite.All (for some operations)</p><p><strong><em>If you want to master yourself on Graph API, Please check out </em></strong><a href="https://www.udemy.com/course/complete-guide-of-microsoft-graph-api-using-powershell/?referralCode=595471271407322E9CF9"><strong>my Udemy Course</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8596253b62a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Quest for Time’s Treasure : Journey to a Fuller Life]]></title>
            <link>https://medium.com/@tanmoy6292/the-quest-for-times-treasure-journey-to-a-fuller-life-e71f449c1f4d?source=rss-ac93a5188433------2</link>
            <guid isPermaLink="false">https://medium.com/p/e71f449c1f4d</guid>
            <category><![CDATA[storytelling]]></category>
            <category><![CDATA[time-management]]></category>
            <category><![CDATA[life]]></category>
            <category><![CDATA[adventure-travel]]></category>
            <dc:creator><![CDATA[Tanmoy Naiya]]></dc:creator>
            <pubDate>Thu, 24 Apr 2025 08:02:00 GMT</pubDate>
            <atom:updated>2025-04-24T08:02:00.298Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Quest for Time’s Treasure : Journey to a Fuller Life</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4xnHpyCSvhn9GERkWNaGrQ.jpeg" /></figure><p>In a quaint town, there lived a man named Alex. He was 30 years old and had already burned through almost half of the days of his life. One day, while reflecting on his journey, he realized that time wasn’t just slipping away — it was sprinting. This realization hit him hard, and he wondered if there was a way to slow it down.</p><p>Alex stumbled upon a fascinating concept: his brain made years disappear as he aged, but new experiences could rewire his perception and make time expand again. Determined to make the most of his remaining days, Alex decided to take different routes, talk to strangers, and break his routines. He embraced the idea that life was about creating memorable moments, not just going through the motions.</p><p>He started with small changes. Instead of taking the same path to work every day, he explored new streets and discovered hidden gems in his town. He struck up conversations with people he met along the way, learning about their stories and gaining new perspectives. These interactions enriched his life and made each day feel longer and more meaningful.</p><p>Alex also adopted the “deathbed test” — would he care about that extra hour at work or the moments stolen from loved ones? He realized that relationships weren’t built on grand gestures but on small, meaningful actions. A text, a shared struggle, a remembered detail — these were the building blocks of strong connections. He made an effort to be present for his friends and family, cherishing the time spent with them.</p><p>In his career, Alex learned that success wasn’t found in his comfort zone but one step beyond it. He embraced challenges and took risks, knowing that jungle gyms beat ladders every time. His biggest mistake had been thinking that morning him and evening him were the same person. He started to recognize the different needs and energies he had throughout the day, adjusting his activities accordingly.</p><p>Health became a priority for Alex, not just to live longer but to live fuller. He realized that 10 push-ups now beat two hours at the gym someday. He incorporated small, consistent habits into his daily routine, which made a significant impact on his overall well-being.</p><p>Alex understood that life design wasn’t a rigid plan but a series of experiments. Tiny changes today could create avalanches tomorrow. He began to see his 30,000 days as an opportunity to craft a life filled with purpose and joy.</p><p>As Alex continued his journey, he felt a profound sense of fulfillment. He had learned to slow down time by embracing new experiences, nurturing relationships, and stepping out of his comfort zone. His life was richer and more vibrant, and he made every moment count.</p><p>And so, Alex lived his days with intention and gratitude, knowing that each one was a precious gift. His journey was a testament to the power of small changes and the importance of living a fuller life.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e71f449c1f4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reclaiming Time: Maya’s Journey from Digital Quicksand]]></title>
            <link>https://medium.com/@tanmoy6292/reclaiming-time-mayas-journey-from-digital-quicksand-001f4c9a8dee?source=rss-ac93a5188433------2</link>
            <guid isPermaLink="false">https://medium.com/p/001f4c9a8dee</guid>
            <category><![CDATA[storytelling]]></category>
            <category><![CDATA[focus]]></category>
            <category><![CDATA[time-management]]></category>
            <category><![CDATA[attention]]></category>
            <dc:creator><![CDATA[Tanmoy Naiya]]></dc:creator>
            <pubDate>Wed, 23 Apr 2025 18:28:31 GMT</pubDate>
            <atom:updated>2025-04-23T18:28:31.518Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wfv5bIyqc8kPWIX5RFgSWg.jpeg" /></figure><p>Once upon a time, in a bustling city where everyone seemed to be in a constant rush, there lived a young woman named Maya. Maya was always glued to her smartphone, her fingers dancing across the screen as she scrolled through endless feeds and notifications. She often found herself lost in the digital world, unaware of the time slipping away.</p><p>One sunny afternoon, Maya decided to take a break from her work and check her phone. What she thought would be a quick glance turned into an hour-long dive into social media. When she finally looked up, she was shocked to realize how much time had vanished. It felt like she had been caught in digital quicksand, where her attention was the most valuable currency.</p><p>Maya’s smartphone wasn’t just a tool; it was an attention vampire, hijacking her brain’s reward system. She had voluntarily installed a 24/7 distraction machine in her pocket. The shocking reality hit her: it took 23 minutes to fully refocus after a single notification. This wasn’t just wasted time; it was creating attention residue that prevented her from doing deep, meaningful work. A simple notification about her cousin’s lunch had cost her half an hour of productive time.</p><p>The myth of multitasking was crushing her productivity by 40%. Her brain didn’t juggle tasks; it rapidly switched between them, paying a mental toll each time. But Maya realized there was hope. She could train her focus like a muscle, working with her brain’s natural ultradian rhythms and practicing single-tasking to enter the flow state, where she could be 500% more productive.</p><p>Maya understood that her brain was not a machine; it was a high-performance organism that needed strategic maintenance. She began to make changes in her life, setting boundaries with her phone, and dedicating time to single-tasking. Slowly but surely, she noticed a significant improvement in her productivity and overall well-being.</p><p>In the end, Maya learned that her life became what she paid attention to. She decided to make it count, focusing on what truly mattered and reclaiming her time from the clutches of digital quicksand. And so, she lived a more mindful and fulfilling life, one task at a time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=001f4c9a8dee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrate Azure KeyVault with Azure Function to store secrets]]></title>
            <link>https://medium.com/@tanmoy6292/integrate-azure-keyvault-with-azure-function-to-store-secrets-42bfe5399a79?source=rss-ac93a5188433------2</link>
            <guid isPermaLink="false">https://medium.com/p/42bfe5399a79</guid>
            <category><![CDATA[script]]></category>
            <category><![CDATA[azure-key-vault]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[azure-functions]]></category>
            <category><![CDATA[powershell]]></category>
            <dc:creator><![CDATA[Tanmoy Naiya]]></dc:creator>
            <pubDate>Wed, 23 Oct 2024 10:18:37 GMT</pubDate>
            <atom:updated>2025-04-23T10:40:24.212Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x2xnOnNPHqa1jlki" /><figcaption>Photo by <a href="https://unsplash.com/@bergerteam?utm_source=medium&amp;utm_medium=referral">Florian Berger</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Why we need to integrate Azure KeyVault with Azure Function?</h3><p>As we all know, we can always use the azure function settings and go to “Environment Variable” to set the environment variables and that is the most obvious way to handle your environment variables but sometimes there are secrets which needs to be protected from other users who have similar kind of access of the subscription in your tenant. In that case azure keyvault would be the ideal way to store the secrets and can be used by azure functions directly without revealing the value of those secrets.<br>I do understand azure keyvault comes with some cost but that is very minimal and worth using when there is question of security.</p><h3>How to integrate Azure Key Vault with Azure Function?</h3><h4>1. Create Azure Function App:</h4><p>Create you azure function app first in-order to integrate with azure keyvault. If you are not familiar with how to create Azure function App, follow this <a href="https://learn.microsoft.com/en-us/azure/azure-functions/functions-get-started?pivots=programming-language-powershell">Microsoft document</a></p><h4>2. Create a system assigned Identity</h4><p>Once you have created the azure function App, you need to create a system assigned Identity of the Function App which we have just created. Click on <strong>Settings -&gt; Identity. </strong>Switch the status “On” under System assigned tab as below.<br>Object ID will be created for your function App once the status is switched to “On”. Copy this Object ID and keep it in a safe place, we will use this ID at the time of the integration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*quQPLK8U6xYQdYHAJ2u-jA.png" /></figure><blockquote><strong>If you want to master yourself on Graph API, Please check out </strong><a href="https://www.udemy.com/course/complete-guide-of-microsoft-graph-api-using-powershell/?referralCode=595471271407322E9CF9"><strong><em>my Udemy Course</em></strong></a></blockquote><h4>3. Create Azure Key Vault</h4><p>Create your azure key vault from the portal or CLI to store your secrets. If you are not familiar with azure key vault. Please follow <a href="https://learn.microsoft.com/en-us/azure/key-vault/secrets/quick-create-portal">this Microsoft document</a>.</p><h4>4. Create Access Policies of Azure Key Vault</h4><p>Create a access policy for the azure key vault so that your azure function app can access it. Go to Access Policies and click on “+ Create” as shown below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*rPQ0_bXR_aoVehQKlP4puQ.png" /></figure><p>It will take you to the “Permission” tab where you can select the permissions you want to assign to the azure function app, Here I am only giving “Get” permission for accessing my Secrets. You can give “Set” permission if you want to write secrets in the key vault. Click on “Next”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b-D-dLHXNTx2_reme95VFg.png" /></figure><p>After selecting the permissions it will take you to the “Principal” tab where you can search the “Object ID” which you have copied from azure function app while creating system assigned identity in <strong>step 2. </strong>Select the application and click on “Next”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*38h8ApPwL62WTXyAXYDiyA.png" /></figure><p>No need to select any application in the application tab since it is optional unless you need to add any application explicitly. Click on “Create” to create the access policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*2k5vk0nYkcPS4WSR_HbXRQ.png" /></figure><p>Now, you should see the application under “application” with selected permission as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j-i84w2fM3LPjI0dByUJSA.png" /></figure><h4>5. Create your secrets inside the Key Vault.</h4><p>Now you can create your secrets/certificates/keys inside the key vault as per your requirement. I have created secrets only called “RefreshToken” as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l69MpP8Ulv7Cn3ivS0WCUQ.png" /></figure><p>Now click on the scret you have just created, Now you may see multiple versions of the secrets if you have already created several versions. Click on the version you want to use. Now copy the “Secret Identifier” as shown in the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*RDdwm4rhWtoQfth9rKoiUg.png" /></figure><h4>6. Configure the Azure Function</h4><p>Now go to your Azure function and create an environment varibale as per your requirement, I am naming it as “RefreshToken”. The value should contains like below. Click on “Apply”</p><blockquote>“<a href="http://twitter.com/Microsoft">@Microsoft</a>.KeyVault(SecretUri=CopiedURL)”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_oF-CL_4thcD1_QqBr-mUw.png" /></figure><p>Once saved the source should say “Key Vault” and ticked on green as below. Now you are ready to use the secrets inside your azure function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aZ2o-YlyRVkNePoyzSBgjg.png" /></figure><p>Thanks for reading till here. Please comment if you have any queries.</p><p>Read all <a href="https://medium.com/@tanmoy6292">my articles</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42bfe5399a79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Resource Owner Password Credentials(ROPC) OAuth in PowerShell]]></title>
            <link>https://medium.com/@tanmoy6292/resource-owner-password-credentials-ropc-oauth-in-powershell-472dee8b5be4?source=rss-ac93a5188433------2</link>
            <guid isPermaLink="false">https://medium.com/p/472dee8b5be4</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[azure-functions]]></category>
            <category><![CDATA[azure-devops]]></category>
            <category><![CDATA[powershell]]></category>
            <category><![CDATA[microsoft-graph-api]]></category>
            <dc:creator><![CDATA[Tanmoy Naiya]]></dc:creator>
            <pubDate>Tue, 03 Sep 2024 13:03:35 GMT</pubDate>
            <atom:updated>2025-04-23T10:41:14.419Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xEEM80EY_HsEOEKn" /><figcaption>Photo by <a href="https://unsplash.com/@windows?utm_source=medium&amp;utm_medium=referral">Windows</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We have already discussed on how to get <a href="https://medium.com/@tanmoy6292/get-access-token-for-graph-api-in-powershell-19a15087fd96">application token</a> and <a href="https://medium.com/@tanmoy6292/get-refresh-token-and-access-token-for-ms-graph-api-in-powershell-delegated-permission-1f67f781ceb6">delgated token</a> for Graph API in PowerShell in our previous blogs. Today we will be seeing how to generate resource owner password credentials (ROPC) OAuth for Graph API in PowerShell.</p><p>Microsoft identity platform allows the resource owner password credentials oath which means user can authenticate directly by handling their password in the application. Below is the protocol diagram of how it works.</p><blockquote><strong>If you want to master yourself on Graph API, Please check out </strong><a href="https://www.udemy.com/course/complete-guide-of-microsoft-graph-api-using-powershell/?referralCode=595471271407322E9CF9"><strong><em>my Udemy Course</em></strong></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*IWo3LlDsY57CqrIc2HH0sA.png" /></figure><h4>Warning!</h4><blockquote>Microsoft recommends you do <em>not</em> use the ROPC flow. In most scenarios, more secure alternatives are available and recommended like application and delgation authentication token. This flow requires a very high degree of trust in the application, and carries risks that are not present in other flows. You should only use this flow when other more secure flows aren’t viable for your soultion.</blockquote><p>As this(ROPC) authentication flow has some vulnaribilities, it also comes with some limitations. Please read below poits before implementing it to your solution.</p><h4>Important!</h4><blockquote>1. The Microsoft identity platform only supports the ROPC grant within Microsoft Entra tenants, not personal accounts. This means that you must use a tenant-specific endpoint (https://login.microsoftonline.com/{TenantId_or_Name}) or the organizations endpoint.</blockquote><blockquote>2. Personal accounts that are invited to a Microsoft Entra tenant can’t use the ROPC flow.</blockquote><blockquote>3. Accounts that don’t have passwords can’t sign in with ROPC, which means features like SMS sign-in, FIDO, and the Authenticator app won’t work with that flow. If your app or users require these features, use a grant type other than ROPC.</blockquote><blockquote>4. If users need to use <a href="https://learn.microsoft.com/en-us/entra/identity/authentication/concept-mfa-howitworks">multi-factor authentication (MFA)</a> to log in to the application, they will be blocked instead.</blockquote><blockquote>5. ROPC is not supported in <a href="https://learn.microsoft.com/en-us/entra/identity/hybrid/connect/whatis-fed">hybrid identity federation</a> scenarios (for example, Microsoft Entra ID and AD FS used to authenticate on-premises accounts). If users are full-page redirected to an on-premises identity provider, Microsoft Entra ID is not able to test the username and password against that identity provider. <a href="https://learn.microsoft.com/en-us/entra/identity/hybrid/connect/how-to-connect-pta">Pass-through authentication</a> is supported with ROPC, however.</blockquote><blockquote>6. An exception to a hybrid identity federation scenario would be the following: Home Realm Discovery policy with AllowCloudPasswordValidation set to TRUE will enable ROPC flow to work for federated users when an on-premises password is synced to the cloud. For more information, see <a href="https://learn.microsoft.com/en-us/entra/identity/enterprise-apps/home-realm-discovery-policy#enable-direct-ropc-authentication-of-federated-users-for-legacy-applications">Enable direct ROPC authentication of federated users for legacy applications</a>.</blockquote><blockquote>7. Passwords with leading or trailing whitespaces are not supported by the ROPC flow.</blockquote><h4>Get the Access Token</h4><p>Once you have understand the flow and <a href="https://medium.com/@tanmoy6292/all-you-need-to-know-while-creating-app-service-principal-in-azure-4a31e6b5329">created the application</a>, now it is time to get the access token.<br>Below is the PowerShell code to get the access token.</p><pre># Set your clientID, TenantID and the app secret<br>$AzureADAppClientId = &quot;xxx-xxx-xxx&quot;<br>$AzureADAppClientSecret = &quot;xxx-xxx-xxx&quot;<br>$AzureADTenantId = &quot;xxx-xxx-xxx&quot;<br>$user = &quot;user-email-without-MFA&quot;<br>$password = &quot;raw-password&quot;<br><br>function get_ROPC_token()<br>{    <br>    # Application (client) ID, tenant ID and secret<br>    $clientId = $AzureADAppClientId<br>    $tenantId = $AzureADTenantId<br>    $clientSecret = $AzureADAppClientSecret<br><br>    <br>    # Construct URI<br>    $uri = &quot;https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token&quot;<br>    # Construct Body<br>    $body = @{<br>        client_id     = $clientId<br>        scope         = &quot;https://graph.microsoft.com/.default&quot;<br>        username      = $user<br>        password      = $password<br>        grant_type    = &quot;password&quot;<br>        client_secret = $clientSecret<br>    }<br>    # Get OAuth 2.0 Token<br>    $tokenRequest = Invoke-WebRequest -Method Post -Uri $uri -ContentType &quot;application/x-www-form-urlencoded&quot; -Body $body -UseBasicParsing<br>    # Access Token<br>    $token = ($tokenRequest.Content | ConvertFrom-Json).access_token<br>    return $token<br>}<br><br><br>$token = get_ROPC_token</pre><p>Now you can automate you solution with this token.<br>Please do comment if you have any concern regarding Graph API..</p><ul><li><a href="https://medium.com/@tanmoy6292/get-access-token-for-graph-api-in-powershell-19a15087fd96">Get Access Token for Graph API in PowerShell (Application permission)</a></li><li><a href="https://medium.com/@tanmoy6292/get-refresh-token-and-access-token-for-ms-graph-api-in-powershell-delegated-permission-1f67f781ceb6">Get Refresh Token and Access Token for MS Graph API in PowerShell (Delegated permission)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=472dee8b5be4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Add users to private channels of a Teams using Graph API(PowerShell)]]></title>
            <link>https://medium.com/@tanmoy6292/add-users-to-private-channels-of-a-teams-using-graph-api-powershell-bfd1b7b735b6?source=rss-ac93a5188433------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfd1b7b735b6</guid>
            <category><![CDATA[microsoft-365]]></category>
            <category><![CDATA[access-token]]></category>
            <category><![CDATA[microsoft-teams]]></category>
            <category><![CDATA[powershell]]></category>
            <category><![CDATA[microsoft-graph-api]]></category>
            <dc:creator><![CDATA[Tanmoy Naiya]]></dc:creator>
            <pubDate>Fri, 23 Aug 2024 08:51:22 GMT</pubDate>
            <atom:updated>2025-04-23T10:41:42.920Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RJggX-E16cwPnNqT" /><figcaption>Photo by <a href="https://unsplash.com/@windows?utm_source=medium&amp;utm_medium=referral">Windows</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In my previous post, I have discussed <a href="https://medium.com/@tanmoy6292/backup-teams-private-channel-and-shared-channel-memberships-using-graph-api-powershell-b67184b72286">how to take back-up of a Teams using Graph API</a>. Now it is time to discuss how we can add users if they lose access to any private channels.</p><h4>Why we need to add user to private channels?</h4><p>As an admin if you made any changes to a Teams which has some private channel then there is a chance that some potentials users get removed from your teams. If that user were part of any private channels then simply adding the user to the Teams will not fix the issue as that intended user will not be automatically added to the private channels. In that case either owner of that private channel needs to add the user again manually or as an admin you have to add the user to the channel from the Teams admin center. We will be discussing how we can do that using PowerShell.</p><blockquote><strong>If you want to master yourself on Graph API, Please check out </strong><a href="https://www.udemy.com/course/complete-guide-of-microsoft-graph-api-using-powershell/?referralCode=595471271407322E9CF9"><strong><em>my Udemy Course</em></strong></a></blockquote><h4>Create the application</h4><p>You need to create the Application before you start, I have discussed <a href="https://medium.com/@tanmoy6292/all-you-need-to-know-while-creating-app-service-principal-in-azure-4a31e6b5329">how to create the application here</a>. You can skip this if you already have the application.</p><h4>Add permissions to the application</h4><p>We need to add the permission mentioned in <a href="https://learn.microsoft.com/en-us/graph/api/channel-post-members?view=graph-rest-1.0&amp;tabs=http">Microsoft document</a> as below and get the consent from the admin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*s6ayAgyj-9u6BBokwbGScA.png" /><figcaption>Graph API permission</figcaption></figure><h4>Generate the Token</h4><p>Now that we have the permission granted in our application, We need to generate the token based on our need. <br>To generate Application Token follow <a href="https://medium.com/@tanmoy6292/get-access-token-for-graph-api-in-powershell-19a15087fd96">this blog</a>.<br>To generate Delegated Token follow <a href="https://medium.com/@tanmoy6292/get-refresh-token-and-access-token-for-ms-graph-api-in-powershell-delegated-permission-1f67f781ceb6">this blog</a>.</p><h4>Preapare your input file</h4><p>Before jumping to the PowerShell Script we need to prepare the input file which will be used in our PowerShell script. To create the input file you can <a href="https://medium.com/@tanmoy6292/backup-teams-private-channel-and-shared-channel-memberships-using-graph-api-powershell-b67184b72286">follow this blog</a>. You can create your own input files and change the below scripts accordingly.</p><h4>Prepare the PowerShell Script</h4><p>You can use the below PowerShell script to restore the membership of users of a particular teams or multiple teams.</p><blockquote>Please do remember this script will fail if the user is not present in the Teams before trying to add them in a private channel. Make sure that the user is added to the teams before running the script.</blockquote><pre># get the token<br><br>$token = get_token<br>$inputFilePath = $PSScriptRoot<br>$backUpData = Import-Csv -Path &quot;$inputFilePath\Teams_Input_file.csv&quot;<br><br><br>foreach($row in $backUpData){<br>    <br>    # Preparing the URL for adding the user<br>    $addURL =  &quot;https://graph.microsoft.com/v1.0/teams/$($row.TeamsID)/channels/$($row.ChannelID)/members&quot;<br>    $user = $($row.MemberID)<br><br>    # Checking if the user is Owner<br>    if($($row.MemberType) -eq &#39;owner&#39;){<br>        # Preparing Owner body<br>        $postBody = @{<br>            &quot;@odata.type&quot; = &quot;#microsoft.graph.aadUserConversationMember&quot;<br>            &quot;user@odata.bind&quot; = &quot;https://graph.microsoft.com/v1.0/users/$($user)&quot;<br>            &quot;roles&quot;= &#39;[&quot;owner&quot;]&#39;<br><br>        }<br>        $bodyJSON = $postBody | ConvertTo-Json<br>        $post = $($($bodyJSON.Replace(&#39;&quot;[\&#39;,&quot;[&quot;)).replace(&#39;]&quot;&#39;,&quot;]&quot;)).replace(&quot;\&quot;,&quot;&quot;)<br>        Invoke-RestMethod -Uri $addURL -Method POST -Body $post -Headers @{Authorization = &quot;Bearer $token&quot;} -ContentType &#39;application/json&#39;<br><br>    }<br>    else{<br><br>    # Preparing Member body<br>        $postBody = @{<br>            &quot;@odata.type&quot; = &quot;#microsoft.graph.aadUserConversationMember&quot;<br>            &quot;user@odata.bind&quot; = &quot;https://graph.microsoft.com/v1.0/users/$($user)&quot;<br><br>        }        <br>        $bodyJSON = $postBody | ConvertTo-Json<br><br>        Invoke-RestMethod -Uri $addURL -Method POST -Body $bodyJSON -Headers @{Authorization = &quot;Bearer $token&quot;} -ContentType &#39;application/json&#39;<br>     }<br>}</pre><p>Once you run the script it should return result like below for each successfull iteration(adding users in channel).</p><figure><img alt="Add users to private channels in Teams" src="https://cdn-images-1.medium.com/max/1024/1*Lwc5ExRZubLf8JIAKOPMhw.png" /><figcaption>Add users to private channels</figcaption></figure><p>Thanks for reading this blog till here.</p><p>Please comment if you have any queries on Graph API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sU9TtCqSdvdhxWCw" /><figcaption>Photo by <a href="https://unsplash.com/@manucosen?utm_source=medium&amp;utm_medium=referral">Manuel Cosentino</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfd1b7b735b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Backup Teams private channel and shared channel memberships using Graph API — PowerShell]]></title>
            <link>https://medium.com/@tanmoy6292/backup-teams-private-channel-and-shared-channel-memberships-using-graph-api-powershell-b67184b72286?source=rss-ac93a5188433------2</link>
            <guid isPermaLink="false">https://medium.com/p/b67184b72286</guid>
            <category><![CDATA[team-members]]></category>
            <category><![CDATA[microsoft-graph-api]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[powershell]]></category>
            <category><![CDATA[microsoft-teams]]></category>
            <dc:creator><![CDATA[Tanmoy Naiya]]></dc:creator>
            <pubDate>Fri, 09 Aug 2024 10:31:53 GMT</pubDate>
            <atom:updated>2025-04-23T10:42:21.613Z</atom:updated>
            <content:encoded><![CDATA[<h3>Backup Teams private channel and shared channel memberships using Graph API — PowerShell</h3><figure><img alt="Teams private channel membership" src="https://cdn-images-1.medium.com/max/874/1*M6sDkGpfgKHEpt3NYNyVmQ.png" /></figure><p>We have already discussed how we can get full list of Teams and corresponding channels insie an organization using Graph API(PowerShell) <a href="https://medium.com/@tanmoy6292/extract-all-teams-and-channels-details-using-graph-api-powershell-in-your-organization-f8f3e496049d">in this blog</a>.<br>Today we will be discussing how we can take backup of Teams private/shared channel memberships.</p><blockquote><strong>If you want to master yourself on Graph API, Please check out </strong><a href="https://www.udemy.com/course/complete-guide-of-microsoft-graph-api-using-powershell/?referralCode=595471271407322E9CF9"><strong><em>my Udemy Course</em></strong></a></blockquote><h4>Why do we need private/shared channel membership backup?</h4><p>As an admin of your organization, you sometimes need to modify the memberships of a Teams specially if those Teams are dynamic. During the process if some potential users got removed from the Teams, he/she will loose Private channel membership even if you add the user again to the Teams.<br>That is why it is always a good idea to take backup of membership details, so that you can restore the membership again using the backup. I will write a blog on “How to restore the Teams Private memberships”.</p><h4>Preparation to take backup</h4><p>All we need a list of Teams for which we want to take the backup in a CSV file like below (you can take this input in any format, I am using CSV only) where we need, Teams Name and Teams ID. You can collect this information from your Azure portal (Group name and group id of the Teams) or from the Teams details.</p><figure><img alt="Teams List" src="https://cdn-images-1.medium.com/max/759/1*4VOamVHt4G3kdzOwBhvkLg.png" /></figure><h4>Get the Application permission for your application</h4><p>Unfortunately, this feature isn’t available for delegated permission. we you need to get the application permission as mentioned <a href="https://learn.microsoft.com/en-us/graph/api/channel-list-members?view=graph-rest-1.0&amp;tabs=http">in this Microsoft Documentation.</a></p><h4>Get your Application Token</h4><p>After getting the application permission approved/granted for your application, we can start preparing for taking the membership backup. Before that we need to get the access token to start. I have written a detailed blog on <a href="https://medium.com/@tanmoy6292/get-access-token-for-graph-api-in-powershell-19a15087fd96">how to get Application access token</a></p><h4>PowerShell Script to take membership backup</h4><p>Below is the full PowerShell script to take private/shared channel membership backup after you have got the token.</p><blockquote>We have also taken the role of the member in that channel, It will help while restoring the membership if needed.</blockquote><pre># Get the token (https://medium.com/@tanmoy6292/get-access-token-for-graph-api-in-powershell-19a15087fd96)<br>$token = get_token<br><br># Store the CSV file in the same folder where the script is running.<br>$teamsList = Import-Csv -Path &quot;$PSScriptRoot\TeamsList.csv&quot;<br><br>foreach($teams in $teamsList){<br><br>    # URL to get channels<br>    $url = &quot;https://graph.microsoft.com/v1.0/teams/$($teams.TeamsID)/channels&quot;<br>    # Get all the channels<br>    $channels =Invoke-RestMethod -Method GET -Uri $url -Headers @{Authorization = &quot;Bearer $token&quot;} -ContentType &#39;application/json&#39;<br><br>    foreach($channel in $channels.value){<br><br>        if(($channel.membershipType -eq &#39;private&#39;) -or ($channel.membershipType -eq &#39;unknownFutureValue&#39;))<br>        {<br>            # URL to get channel members<br>            $membersURL = &quot;https://graph.microsoft.com/v1.0/teams/$($teams.TeamsID)/channels/$($channel.id)/members&quot;<br>            do{<br>                # Get members from the channels<br>                $channelMemebers =Invoke-RestMethod -Method GET -Uri $membersURL -Headers @{Authorization = &quot;Bearer $token&quot;} -ContentType &#39;application/json&#39;<br>                $membersURL = $channelMemebers.&#39;@odata.nextLink&#39;<br>                foreach($member in $channelMemebers.value){<br><br>                    $obj = [PSCustomObject]@{<br>                        Teams = $teams.Teams<br>                        TeamsID = $teams.TeamsID<br>                        ChannelName = $channel.displayName<br>                        ChannelID = $channel.id<br>                        ChannelType = $channel.membershipType<br>                        MemberName = $member.displayName<br>                        MemberID = $member.userId<br>                        MemberEmail = $member.email<br>                        MemberType =  $($member.roles -join(&quot;,&quot;))<br>                    }<br>                    #$obj | fl<br>                    $obj | Export-Csv -Path &quot;$PSScriptRoot\TeamsBackup.csv&quot; -NoTypeInformation -Append -Encoding UTF8<br>                }<br><br>            }<br>            until(!$membersURL)<br>        }<br>    }<br><br>}</pre><p>This will generate a CSV file with all the necessary details which can be very helpful for future reference if some potential users loose access in Teams.</p><blockquote>Graph API can return many more attribute than what I mentioned here, you can add/remove attributes based on your requirement.</blockquote><p>Thanks for reading, Please comment of you have any query related to Graph API and PowerShell.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b67184b72286" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extract All Teams and Channels Details using Graph API (PowerShell) in your Organization]]></title>
            <link>https://medium.com/@tanmoy6292/extract-all-teams-and-channels-details-using-graph-api-powershell-in-your-organization-f8f3e496049d?source=rss-ac93a5188433------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8f3e496049d</guid>
            <category><![CDATA[microsoft-365]]></category>
            <category><![CDATA[microsoft-teams]]></category>
            <category><![CDATA[powershell]]></category>
            <category><![CDATA[microsoft-graph-api]]></category>
            <category><![CDATA[access-token]]></category>
            <dc:creator><![CDATA[Tanmoy Naiya]]></dc:creator>
            <pubDate>Fri, 02 Aug 2024 08:57:36 GMT</pubDate>
            <atom:updated>2025-04-23T10:42:51.325Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Extract All Teams and Channels Details using Graph API (PowerShell) in your Organization" src="https://cdn-images-1.medium.com/max/1024/1*pN6f-Xs06zAgHqYnUgZZYw.png" /></figure><p>Did you ever faced the challenge as a Microsoft365 admin when someone came to you asking for a Teams channel membership but dont know the Teams name where the channel belongs!! Yes, it is really frustrating to locate the channel manually from the Teams Admin center.</p><p>Today I will discuss, how we can extract a full list of Teams and Channels details using Graph API and write the full PowerShell script so that it can be handy when we face this kind of requirements. Hoping that, this will ease some of Microsoft 365 admins life at some point.</p><h3>Basic Requirements</h3><p>To achive this functionality, we need very basic things as below.<br>1. <a href="https://medium.com/@tanmoy6292/all-you-need-to-know-while-creating-app-service-principal-in-azure-4a31e6b5329">Register an App in Azure.</a><br>2. Get the permissions mentioned in <a href="https://learn.microsoft.com/en-us/graph/api/channel-list?view=graph-rest-1.0&amp;tabs=http">Graph API documentation</a> by Microsoft. (We need two kind of permission, one for getting all the groups details which has Teams and another for listing all channels inside a Teams).<br>3. Get the admin consent for all the permissions from a global admin(if you are not a Global admin).</p><blockquote><strong>If you want to master yourself on Graph API, Please check out </strong><a href="https://www.udemy.com/course/complete-guide-of-microsoft-graph-api-using-powershell/?referralCode=595471271407322E9CF9"><strong><em>my Udemy Course</em></strong></a></blockquote><h3>Get the Access Token</h3><p>Unfortunately, this doesn’t supported for delegated permission. So we have to get the Access Token for Application Permission. To generate the Access Token you can <a href="https://medium.com/@tanmoy6292/get-access-token-for-graph-api-in-powershell-19a15087fd96">follow this article.</a></p><blockquote>If you are looking for generating Access Token for Delegated permission then you can f<a href="https://medium.com/@tanmoy6292/get-refresh-token-and-access-token-for-ms-graph-api-in-powershell-delegated-permission-1f67f781ceb6">ollow this article.</a></blockquote><h3>List all the Groups which has Teams</h3><p>To get all the Teams details in your organization, you need to get all the groups in your organization and then filter the groups which has Teams attached with it. We can do that by a very simple PowerShell script like below.</p><pre># get the access token, to get the token Follow the article I mentioned above<br><br>$token = get_token<br><br># Get all the groups and filter only Teams Groups<br><br>$teamsURL = &quot;https://graph.microsoft.com/v1.0//groups?`$filter=resourceProvisioningOptions/Any(x:x eq &#39;Team&#39;)&quot;<br><br>do{  <br>    $teams = Invoke-RestMethod -Method GET -Uri $teamsURL -Headers @{Authorization = &quot;Bearer $token&quot;} -ContentType &#39;application/json&#39;<br>    $teamsURL = $teams.&#39;@odata.nextLink&#39;<br>}<br>until(!$teamsURL)</pre><h3>Common mistake</h3><blockquote>A common mistake might happen here while running this query in PowerShell if you did not copy exactly from above script and only followed Microsoft documentation. Did you notice the “ ` ” sign between ? and $ like below.<br>if you ignore this, PowerShell will think that $filter is a variable and it will corrupt your URL, so you will not get your desired filtered result.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n7AbX14VaPChDbrdPuG-qA.png" /><figcaption>be careful</figcaption></figure><h3>Loop through all Teams and get all channels</h3><p>Now that we have got all the Teams details in our organization, we can loop through all the Teams and get all the channels in it like below.</p><h3>Full PowerShell Script</h3><pre><br># Get the date and Script location (Optional)<br>$date = Get-Date -Format &#39;yyyyMMdd&#39;<br>$path = $PSScriptRoot<br><br># get the access token, to get the token Follow the article I mentioned above<br>$token = get_token<br><br># Get all the groups and filter only Teams Groups<br><br>$teamsURL = &quot;https://graph.microsoft.com/v1.0//groups?`$filter=resourceProvisioningOptions/Any(x:x eq &#39;Team&#39;)&quot;<br><br>do{  <br>    $teams =Invoke-RestMethod -Method GET -Uri $teamsURL -Headers @{Authorization = &quot;Bearer $token&quot;} -ContentType &#39;application/json&#39;<br>    $teamsURL = $teams.&#39;@odata.nextLink&#39;<br><br>    foreach($team in $teams.value){<br>        # get the channels<br>        $channelURL = &quot;https://graph.microsoft.com/v1.0/teams/$($team.id)/channels&quot;<br>        $channels =Invoke-RestMethod -Method GET -Uri $channelURL -Headers @{Authorization = &quot;Bearer $token&quot;} -ContentType &#39;application/json&#39;<br>        foreach($channel in $channels.value){<br>            $obj = [PSCustomObject]@{<br>                TeamsID = $team.id<br>                TeamsName = $team.displayName<br>                TeamsVisibility = $team.visibility<br>                TeamsDescription = $team.description<br>                ChannelID = $channel.id<br>                ChannelName = $channel.displayName<br>                ChannelType = $channel.membershipType<br>                ChannelDescription = $channel.description<br>                isArchive = $channel.isArchived<br>            }<br>            $obj | fl<br>            $obj | Export-Csv &quot;$path\All_Teams_Channels_Details_$date.csv&quot; -Append -NoTypeInformation -Encoding UTF8<br>        }<br>    }<br><br>}<br>until(!$teamsURL)</pre><p>You should get details printed on your screen like below.</p><figure><img alt="Teams and Channels Details" src="https://cdn-images-1.medium.com/max/1024/1*1RRf5wrqwhxOhuo57bTesw.png" /><figcaption>Teams and Channels details</figcaption></figure><p>Thanks for reading this article till here..</p><p>Comment if you have any queries!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8f3e496049d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get Refresh Token and Access Token for MS Graph API in PowerShell (Delegated permission)]]></title>
            <link>https://medium.com/@tanmoy6292/get-refresh-token-and-access-token-for-ms-graph-api-in-powershell-delegated-permission-1f67f781ceb6?source=rss-ac93a5188433------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f67f781ceb6</guid>
            <category><![CDATA[microsoft-graph-api]]></category>
            <category><![CDATA[delegated-administrator]]></category>
            <category><![CDATA[refresh-token]]></category>
            <category><![CDATA[powershell-script]]></category>
            <category><![CDATA[microsoft-azure]]></category>
            <dc:creator><![CDATA[Tanmoy Naiya]]></dc:creator>
            <pubDate>Fri, 26 Jul 2024 13:45:43 GMT</pubDate>
            <atom:updated>2025-04-23T10:43:30.082Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="MS graph delegated permission" src="https://cdn-images-1.medium.com/max/443/1*XWpNSyBH8sfNZqSvrvnQZQ.png" /><figcaption>MS graph delegated permission</figcaption></figure><p>We have seen how to get acess token for MS Graph API of Application Permission <a href="https://medium.com/@tanmoy6292/get-access-token-for-graph-api-in-powershell-19a15087fd96">in this blog</a>. but sometimes it is hard to get application permission from admins of a large organizations, as there are some risk involved with application permission if it is not utilized properly. People can anonymously access the data if they have the access token.</p><h4>Background of Delegated Permission</h4><p>Unlike Application permission(app only access), Delegated permission works on behalf of an user, that means an user must login to get the access token and that token contailns all the necessary information regarding the logged in users as well as the application. In this way it is easy for admins to track on the activities made by the app as well as who is the user behind the app.</p><blockquote><strong>If you want to master yourself on Graph API, Please check out </strong><a href="https://www.udemy.com/course/complete-guide-of-microsoft-graph-api-using-powershell/?referralCode=595471271407322E9CF9"><strong><em>my Udemy Course</em></strong></a></blockquote><h4>Requirement for Delegated permission</h4><p>Let’s discuss what we need in-order to work with delegated permission.</p><p><strong>Req 1: </strong>We need an azure service principal(app registration). If you do not have one yet, <a href="https://medium.com/@tanmoy6292/all-you-need-to-know-while-creating-app-service-principal-in-azure-4a31e6b5329">create an azure service principal.</a></p><p><strong>Req 2:<em> </em></strong>Gather<strong><em> App_ID, Tenant_ID, Client_Secret</em></strong> and <strong><em>Redirect_URL</em></strong> from the application. <br><strong><em>* Redirect_URL </em></strong>is very crucial here, as without it you cant get the authorization code.<br>A redirect URI, or reply URL, is the location where the Microsoft Entra authentication server sends the user once they have successfully authorized and provide the authorization code which can be used to get an access token. <br><strong><em>** </em></strong>You can provide any valid url as redirect url, I am keeping it as “https://portal.azure.com/” as I wanted to get this page to open after my login.</p><figure><img alt="Redirect URL" src="https://cdn-images-1.medium.com/max/1024/1*XclWQ0LIvS3f1S1DYM4mcg.png" /><figcaption>Redirect URL</figcaption></figure><h4>Get ready to fetch Authorization Code</h4><p>We need to get an authorization code before trying to fetch the access token or refresh token.<br>To get the authorization code we need to prepare below URL and try to access it in a browser.</p><pre>https://login.microsoftonline.com/{tenant_ID}/oauth2/v2.0/authorize?client_id={App_ID}&amp;response_type=code&amp;redirect_uri={redirect_url}&amp;response_mode=query&amp;scope=offline_access%20user.read&amp;state=12345</pre><p><strong><em>*** </em></strong>Change the URL with your <strong><em>tenant_ID, App_ID</em></strong> and <strong><em>redirect_url </em></strong>as per your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cTYoXusb_KoyX_1fKbLEKw.png" /><figcaption>get the authorization code</figcaption></figure><blockquote>If the redirect URI specified in the login request doesn’t match any of the redirect URIs you have added in your application, you receive an error message such as AADSTS50011: The reply URL specified in the request does not match the reply URLs configured for the application.</blockquote><h4>Get the Authorization Code</h4><p>If above url works fine for you and able to successfully logged in then you will be landing to the redirect_URL which you have provided (in my case it is azure portal). Now if you notice the <strong>address bar</strong> of your browser, you will see a code there as shown in the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*btmcguSvy27S3_wdBDpGxQ.png" /><figcaption>Auth code</figcaption></figure><p>Now copy the <strong>code</strong> and remove the part “<strong>&amp;state=12345&amp;session_state….</strong>”.<br>You should have “<strong>code = 0.AS8AC__….</strong>”</p><blockquote>Now save the code somewhere before jumping to actual powershell coding, remember <strong>this code can be used only once</strong> in your PowerShell script to get access token and it is valid around 10 mins. I have discussed the possible errors below.</blockquote><h4>Get the Access Token and Refresh Token</h4><p>Now that we have the <strong>auth_code</strong>, we can utilize the <strong>auth_code</strong> to retrive the Access Token and the Refresh Token.</p><pre># App_ID, Tenant_ID, Client_Secret and redirect URL<br>$AzureADAppClientId = &quot;XXX-XXX&quot;<br>$AzureADTenantId = &quot;XXX-XXX&quot;<br>$AzureADAppClientSecret = &quot;XXX-XXX&quot;<br>$redirect_URL = &quot;https://bla-bla...&quot;<br><br># Change the auth_code here..<br>$code = &quot;0.XXX-XXX-XXX&quot;<br><br> # Application (client) ID, tenant ID and secret<br>    $clientId = $AzureADAppClientId<br>    $tenantId = $AzureADTenantId<br>    $clientSecret = $AzureADAppClientSecret<br>    $redirect_URL = $redirect_URL<br><br>    <br>    # Construct URI<br>    $uri = &quot;https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token&quot;<br>    # Construct Body<br>    $body = @{<br>        client_id     = $clientId<br>        scope         = &quot;User.Read&quot;<br>        code          = $code<br>        grant_type    = &quot;authorization_code&quot;<br>        client_secret = $clientSecret<br>        redirect_uri  = $redirect_URL<br>        <br>    }<br>    # Get OAuth 2.0 Token<br>    $tokenRequest = Invoke-WebRequest -Method Post -Uri $uri -ContentType &quot;application/x-www-form-urlencoded&quot; -Body $body -UseBasicParsing<br>    # Access Token<br>    $Access_token = ($tokenRequest.Content | ConvertFrom-Json).access_token<br><br>    # Refresh Token<br>    $refreshToken = ($tokenRequest.Content | ConvertFrom-Json).refresh_token<br></pre><h4>Possible Errors</h4><p><strong>Error 1: </strong>AADSTS54005: OAuth2 Authorization code was already redeemed, please retry with a new valid code or use an existing refresh token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*_Vq1AzaExcJDS2UYE0_vjw.png" /></figure><p>You will get below error if you are trying to get the Access Token and Refresh Token from the Auth_code which has been used already(It is valid for 1 time use only). To solve this you have to send another interactive session for the user to create a new <strong>Auth_code </strong>like mentioned above.</p><p><strong>Error 2:</strong> AADSTS70008: The provided authorization code or refresh token has expired due to inactivity. Send a new interactive authorization request for this user and resource.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FgoGTJl4P_bfCq_W07KxmQ.png" /></figure><p>You will get below error if you are trying to get the Access Token and Refresh Token from the Auth_code which is already been expired due to inactivity(It is valid around 10 mins from the time of creation). To solve this you have to send another interactive session for the user to create a new <strong>Auth_code</strong>.</p><h4>Background of Refresh Token</h4><p>We know that Access Token is short-lived (only live around 65 mins) so you need to renew your access token whenever your access token is expired. In other hand Refresh Token is long-lived (upto 7 days). <br>Refresh token is provided with the delegated token so that you can automate your PowerShell script without an interactive login. You can get a new access Token from the Refresh token as many time as you want. Every time you get a new access Token from a Refresh Token, a new Refresh Token will be generated and you can do this up to 90 days until the Refresh token gets expired.<br>So even though Delegated Permission is tied up with a interactive user login still you can automate your PowerShell Script up to 90 days. Thats great!!</p><h4>Renew Access Token from a Refresh Token</h4><p>Now that you have a Refresh Token, you can easily get an Access token from the Refresh token like below.</p><pre># store your refresh token as shown in the previous code<br>$refreshToken = ($tokenRequest.Content | ConvertFrom-Json).refresh_token<br><br>function accessTokenFromRefreshToken()<br>{    <br>    # Application (client) ID, tenant ID and secret<br>    $clientId = $AzureADAppClientId<br>    $tenantId = $AzureADTenantId<br>    $clientSecret = $AzureADAppClientSecret<br><br>    <br>    # Construct URI<br>    $uri = &quot;https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token&quot;<br>    # Construct Body<br>    $body = @{<br>        client_id     = $clientId<br>        refresh_token = $refreshToken<br>        grant_type    = &quot;refresh_token&quot;<br>        client_secret = $clientSecret<br><br>    }<br>    # Get OAuth 2.0 Token<br>    $tokenRequest = Invoke-WebRequest -Method Post -Uri $uri -ContentType &quot;application/x-www-form-urlencoded&quot; -Body $body -UseBasicParsing<br>    # Access Token<br>    $token = ($tokenRequest.Content | ConvertFrom-Json).access_token<br>    return $token<br>}<br><br>$token = accessTokenFromRefreshToken</pre><p>Now that you know how to renew your Access Token, You can easily access any Graph API resources like, Sending messages in Teams chat or Teams channels etc.</p><h4>Conclusion</h4><blockquote>Even though the Application permission is easy to work with and has a lot more potentials than Delegated permission, We some times forced to work with Delegated permissions due to the organizational setup and security measurement.</blockquote><blockquote>Sometimes there are certain API endpoint which does not support Application permission, in that case Delegated permission comes handy…</blockquote><p>Thanks for reading until this point. Please feel free to comment/ask questions..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f67f781ceb6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Desable/Deactivate Slack users in bulk using PowerShell]]></title>
            <link>https://medium.com/@tanmoy6292/desable-deactivate-slack-users-in-bulk-using-powershell-53dace7bd1bb?source=rss-ac93a5188433------2</link>
            <guid isPermaLink="false">https://medium.com/p/53dace7bd1bb</guid>
            <category><![CDATA[slack-apps]]></category>
            <category><![CDATA[powershell]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[slack-tips-and-tricks]]></category>
            <category><![CDATA[slack]]></category>
            <dc:creator><![CDATA[Tanmoy Naiya]]></dc:creator>
            <pubDate>Fri, 19 Jul 2024 13:40:36 GMT</pubDate>
            <atom:updated>2024-07-19T13:42:06.483Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MmPhsZjNp1hJPT3-PqNAWg.png" /></figure><p>If you searched in Google on “How to disable slack users in bulk?” all the suggested link will redirect you to<a href="https://api.slack.com/methods/admin.users.remove"> this page </a>where it is talking about Slack API, but you will notice it also says that <em>“This </em><a href="https://api.slack.com/enterprise/managing"><em>API method</em></a><em> can only be used on </em><a href="https://api.slack.com/enterprise"><em>Enterprise Grid</em></a><em> workspaces.”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0t1exbmwPl4y_mBX4mggUQ.png" /><figcaption>Only works in Enterprise Grid</figcaption></figure><p>So, if you do not have an Enterprise Grid workspace , you will not be abale to utilize this API.</p><p>Today we will learn how to utilize SCIM API to disbale Slack users in bulk using a simple PowerShell Script even though you do not have Enterprise Grid workspace.</p><h3>Create your Application to utilize the SCIM API.</h3><p>In-order to utilize the SCIM API, you need to create a slack application in your workspace.</p><p>Step 1: Go to <a href="https://api.slack.com/apps">your workspace</a> to create your own application.</p><p>Step 2: Click on “Create New App” as shown in the picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uvABixFENAk0fH15dDeXbg.png" /></figure><p>Step 3: Click on “From scratch”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*DUGPD6i7OcU4eTNfD3__Vg.png" /></figure><p>Step 3: Type the App Name, I am keeping it as “Disable-Users”. Pick the workspace in which you are creating the application if you have multiple woroksapce. Click on “Create App” to create your very own first Slack application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*BArrqHX3GScbG_RkvLqOOg.png" /></figure><h3>OAth &amp; Permissions</h3><p>Step1: After creating your application, you will see an window of the application, click on <em>“Permissions”</em> under <em>“Basic Information”</em> tab</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*021DzTkWpDpauMtB7fqWWg.png" /></figure><p>Step 2: Click on “Add an OAth Scope” under “User Token Scopes”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*bRmqvzGGR6ZdrrYgQaJXiQ.png" /></figure><p>Step 3: Select “admin” from the dorpdown. This will make sure that your apploication will be acting like an administrator in your workspace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*9X_Up3bzoXDHonKk4CGvGA.png" /></figure><p>Step 4: Once you have added the scope in your application, You should see the screen like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*mREN8fVb0PMoECPuQm0CqA.png" /></figure><h3>Install the Application in your workspace</h3><p>Click on “Request to Install”, so that it trigger the notification to workspace admins.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0RVoqiRCv0hmrGlJD_Wvxg.png" /></figure><p>Write down some description for your admin about the application and hit “Submit Request”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*2qK1bHEigqiRBoj8TEYm1w.png" /></figure><p>Once your application is approved by the admin you should see the application under “Installed Apps”. you can filter by your name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WYFr4YDZCDCxBk1kMF2Ksg.png" /></figure><h3>Collect OAth token for the App</h3><p>Collect the OAth token for the App under “OAth &amp; Permissions” tab, once the app is installed in your worspace. Remember the oath token will be replaced everytime you re-install this application with updated permissions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*L9Ee8x16LXOtf7L6FdvujQ.png" /></figure><h3>Write the PowerShell Script</h3><p>So we are done with setting up the application(I know , its the boring part). Now we can write the PowerShell script to our life.</p><h3>Extracting all users:</h3><p>Write the simplest script as below to extract all your users details from your workspace.</p><pre>$slackToken = &quot;{Your token which you have collected from the App}&quot;<br><br># Get slack users list, Set the count as per your need<br>$url = &quot;https://api.slack.com/scim/v1/Users?count=6000&quot;<br>$users = Invoke-RestMethod -Method GET -Uri $url -Headers @{Authorization = &quot;Bearer $slackToken&quot;} -ContentType &#39;application/json&#39;</pre><p>If your token is valid you should get result like below. All the necessary data in available in “$users.Resources”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*0pYvtQQb8VZRCkllBQ7fwg.png" /></figure><h3>Get a specific user details</h3><p>We can get a specific user’s details as below</p><pre>$slackToken = &quot;{Your token which you have collected from the App}&quot;<br><br># Get a specific slack user, change the user id<br>$url = &quot;https://api.slack.com/scim/v1/Users/{user-id}&quot;<br><br>$users = Invoke-RestMethod -Method GET -Uri $url -Headers @{Authorization = &quot;Bearer $slackToken&quot;} -ContentType &#39;application/json&#39;</pre><p>The result should looking like below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*R4qWuC99l9ZgBwfS5qd7Hg.png" /></figure><h3>Disable all users in bulk</h3><p>Now, lets write the script by which we can disable users in bulk(Please do not do this to your environment unless it is required)</p><pre>$slackToken = &quot;{Your token which you have collected from the App}&quot;<br> <br># point the csv file where you kept all the user information<br> $slackUserList = Import-Csv -Path &quot;file-location\all_Slack_user.csv&quot;<br><br><br>foreach($member in $slackUserList){<br>  <br>  # Disable members only<br>    if($member.status -eq &#39;Member&#39;){<br>        <br>        $url = &quot;https://api.slack.com/scim/v1/Users/$($member.userid)&quot;<br>        Invoke-RestMethod -Method DELETE -Uri $url -Headers @{Authorization = &quot;Bearer $slackToken&quot;} -ContentType &#39;application/json&#39;<br>        $member.fullname<br>    }<br><br>}<br><br></pre><p>This will disbale all the member from your workspace.</p><blockquote>Note : Please do not disable yourself by the script, then the application will stop working and your script will fail as soon as your account got disabled.</blockquote><p>Thanks for reading until this, Please comment for more clarification.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53dace7bd1bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>