如何使用powershell脚本使用SNOW OAuth REST API验证用户?

时间:2017-05-29 11:00:46

标签: rest powershell servicenow

以下链接我用于验证用户现在进入服务:

res=${?#0} res=${res:+ERROR} res=${res:-OK}; echo $res # res=${?#0} #removes the leading 0 of $? -> empty if success # res=${res:+ERROR} #res is set to ERROR if x is not empty, empty otherwise # res=${res:-OK} #res is set to OK if empty, ERROR otherwise

但我无法得到结果。我得到如下输出:

https://<instance>.-now.com/oauth_token?client_id=<client_key>&client_secret=<client_secret>&username=admin&password=admin

我需要在Powershell脚本中使用SNOW REST API对用户进行身份验证。提前感谢..

1 个答案:

答案 0 :(得分:2)

使用OAuth的第一部分是获取访问令牌,第二部分是利用它来从服务现在实例中获取数据(我已在代码中注释,以便您可以找到每个部分并根据您的实例编辑变量) :

#For getting access token you can use this code:


$username = “admin”

$password = 'Zen123$$'

$ClientID = “62a88515890332007975e610a3216c62”

$ClientSecret = “pass@word1”


$RestEndpoint = ‘https://myinstance.service-now.com/oauth_token.do’

$body = [System.Text.Encoding]::UTF8.GetBytes(‘grant_type=password&username=’+$username+’&password=’+$password+’&client_id=’+$ClientID+’&client_secret=’+$ClientSecret)

$result = Invoke-RestMethod -Uri $RestEndpoint -Body $Body -ContentType ‘application/x-www-form-urlencoded’ -Method Post

$access_token = $result.access_token


#Once you have access token, you can utilize the invoke-restmethod to fetch data from servicenow : 

$URI = ‘https://myinstance.service-now.com/api/now/table/incident?sysparm_limit=1’
$headers = @{“authorization” = “Bearer $access_token”}

$result = Invoke-RestMethod -Uri $URI -Headers $headers
$result