Friday, April 3, 2020

Access Sharepoint online using Azure AD app (Oauth Implicit grant flow)


I worked on a sample ps script that uses ADAL to achieve implicit grant flow and use the access token to access Sharepoint Online resource



Steps

2.      Add client secret

3.      2. Add permission to Sharepoint

4.      3. Run the following in Windows Powershell ISE


Install the ADAL PS module using the below command

Install-Module -Name ADAL.PS


 Sample Script

$authority = "https://login.microsoftonline.com/tenant.onmicrosoft.com"
$resourceUrl =https://tenant.sharepoint.com"
$clientId = "<<application Id>>"
$redirectUri = "https://login.microsoftonline.com/common/oauth2/nativeclient" # you should have marked the app as native client in Azure AD
$clientSecret = ConvertTo-SecureString "<<Client secret>>" -AsPlainText -Force
$tenantId="<<tenant GUID>"
$userID="<<Guid of the user>>"



$response = Get-ADALToken -Resource $resourceUrl  -UserId $userID -ClientId $clientId -UserIdType UniqueId   -Authority $authority -PromptBehavior: Auto -RedirectUri $redirectUri

$token = $response.AccessToken

$headers = @{}
$headers.Add("Accept","application/json")
$headers.Add("Authorization","Bearer $token")

$curl="https://tenant.sharepoint.com/_api/search/query?querytext='test'"
$response1 =  Invoke-RestMethod -Method Get -Uri $curl -Headers $headers -Verbose -ContentType application/json
$response1








No comments:

Post a Comment