Dotcom-Monitor supports monitoring of REST API services secured by OAuth protocol. In this article we will show how to set up a monitoring device for the cases when the target Authentication Server returns access token of Bearer type.
In general, the setup will include the following steps:
- Send a token request to the OAuth2 endpoint to get a bearer token (HTTP Post).
- Retrieve the bearer token from the server response.
- Send a request to the API endpoint using the saved access token.
Let’s assume your web service offers the Сlient Сredentials grant type when the client’s credentials are used instead of the resource owner’s. No authorization code needed in this case to make an access token request to the Authorization Server.
At the first step, to specify the token request to the Authorization Server we need to provide the following request body attributes in the Post Data field:
- client_id – your application identifier, issued upon your application’s first registration at the Authorization Server.
- client_secret– issued upon your application’s first registration at the Authorization Server.
- grant_type – must be set to “client_credentials“.
Also, it is recommended to specify “access_token” as a Keyword in the Content Validation field to validate the response from the server.
Once the server response with the access token has been received, the second step is API availability task configuring.
If the Authentication Server returns access token of Bearer type, the following script can be used to retrieve the token in the Prepare Script section:
string access_token; string TokenAuthorization; // get the authorization response from the first task string json = (Tasks["AuthToken"] as Http).body["//*"]; //retrieve the access token from the response body access_token = ""; if(json.IndexOf("access_token\"") != -1) access_token = json.Substring(json.IndexOf("access_token\"") + "access_token\"".Length); if(json.IndexOf("\"") != -1) access_token = access_token.Substring(access_token.IndexOf("\"") + 1); if(json.IndexOf("\"") != -1) access_token = access_token.Substring(0, access_token.IndexOf("\"")); //set the TokenAuthorization variable TokenAuthorization = "Bearer" + access_token;
The token type is specified explicitly in the script here.