Friday, April 3, 2020

Access Sharepoint online using Azure AD app (Oauth On Behalf Of flow)


I worked on a sample ps script that uses ADAL to achieve On-Behalf-Of flow and use the access token to access Sharepoint Online resource



Steps

2     2.  Add client secret

3      3. Add permission to Sharepoint

4       4. 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 =  "<<application Id>>"     #On-Behalf_of flow- We need to get token for the appid

$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>>"


# I use implicit grant flow to get access token for the application
$response = Get-ADALToken -Resource $resourceUrl  -UserId $userID -ClientId $clientId -UserIdType UniqueId   -Authority $authority -PromptBehavior: Auto -RedirectUri $redirectUri

$token = $response.AccessToken
$spresourceUrl="https://tenant.sharepoint.com/.default"

# I use the access token in assertion to get on-behalf-of access token for the Sharepoint online resource


$body = @{}
$body.Add("grant_type","urn:ietf:params:oauth:grant-type:jwt-bearer")
$body.Add("client_id","$clientId ")
$body.Add("client_secret","$clientSecret")
$body.Add("assertion","$token")
$body.Add("scope","$spresourceUrl")
$body.Add("requested_token_use","on_behalf_of")



$curl="https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"
$res=Invoke-WebRequest -Method POST -Uri $curl -Body $body 
$authtoken =$res.Accesstoken

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

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








No comments:

Post a Comment