Apigee OAuth Tester in Powershell

on Monday, February 5, 2018

New Apigee instances/organizations come with a built in OAuth 2.0 server. Their default security mechanism is an API Key, but they fully support OAuth 2.0 right out of the box.

A new instance will come with an active OAuth 2.0 endpoint deployed to your Dev, Test, and Prod instances.

The default OAuth 2.0 endpoint is very similar to this proxy example. But, the tutorial on Apigee’s website is to send the grant_type as a form parameter. So, a quick swap can change the grant_type lookup:

image_thumb[3]

Once that’s changed over, you’ll need to request an access token from the endpoint. To do this go into one of your applications and get the client_id and client_secret:

image_thumb[7]

And now we can throw this info into a powershell script to get back our bearer token:

$apigeeHost = "{organization}-{environment}.apigee.net"
$clientId = "{your client id}"
$clientSecret = "{your client secret}"

$authUrl = "https://$apigeeHost/oauth/client_credential/accesstoken"
$authHeaders = @{
    "Content-Type" = "application/x-www-form-urlencoded"
}
$authBody = "grant_type=client_credentials" + `
            "&client_id=$clientId" + `
            "&client_secret=$clientSecret"

$authResponse = Invoke-WebRequest -Method POST -Headers $headers -Body $body -Uri $loginUrl

if($response.StatusCode -ne 200) {
    throw ("Authorization Failure`r`n" + $response)
}

$authInfo = ConvertFrom-Json $response.Content

$authInfo

image_thumb[9]

Before making a call to a resource, make sure to setup the resource API Proxy with an OAuth Verification:

image_thumb[15]

image_thumb[17]

You actually only need the <Operation>VerifyAccessToken</Operation>, but it doesn’t hurt to leave the rest.

Now that we have a bearer token, we can use it as an authorization header to make a call to our resource:

# use your resource url here
$resourceUrl = "https://$apigeeHost/sa/quartercalendar/oauth/v1/quarters?quarter=20154"
$resourceHeaders = @{
    Authorization = "Bearer $($authInfo.access_token)"
}
$resourceResponse = Invoke-WebRequest -Method GET -Uri $resourceUrl -Headers $resourceHeaders
ConvertFrom-Json $resourceResponse.Content

image_thumb[13]

0 comments:

Post a Comment


Creative Commons License
This site uses Alex Gorbatchev's SyntaxHighlighter, and hosted by herdingcode.com's Jon Galloway.