# OAuthService

## Overview

The `OAuthService` object provides a robust interface for managing OAuth authentication and handling authorized requests. It allows developers to create, configure, and execute HTTP requests such as GET, POST, PUT, and DELETE, ensuring secure access to resources. Developers can also retrieve and manage tokens for maintaining session continuity with the OAuth provider.

With methods like `createGetRequest()` and `executeRequest()`, the service supports constructing and executing customized requests. Token management is facilitated through methods like `getAccessToken()`, `refreshToken()`, and `revokeToken()`, which ensure proper handling of authentication tokens. The service also includes utilities for token expiration checks and obtaining OpenID tokens where supported.

The `OAuthService` integrates seamlessly with OAuth flows, enabling developers to work efficiently with access and refresh tokens, authorization URLs, and custom request configurations. For additional details about the [OAuth authentication](https://docs.servoy.com/guides/develop/security/authentication#oauth-provider), refer to the [Authentication](https://docs.servoy.com/guides/develop/security/authentication) section of this documentation.

## Methods Summarized

| Type                                                                                                   | Name                                                                              | Summary                                                                                                                                                         |
| ------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [OAuthRequest](https://docs.servoy.com/reference/servoyextensions/server-plugins/oauth/oauthrequest)   | [createDeleteRequest(resourceURL)](#createdeleterequest-resourceurl)              | Create a DELETE request.                                                                                                                                        |
| [OAuthRequest](https://docs.servoy.com/reference/servoyextensions/server-plugins/oauth/oauthrequest)   | [createGetRequest(resourceURL)](#creategetrequest-resourceurl)                    | Create a GET request for a resource.                                                                                                                            |
| [OAuthRequest](https://docs.servoy.com/reference/servoyextensions/server-plugins/oauth/oauthrequest)   | [createPostRequest(resourceURL)](#createpostrequest-resourceurl)                  | Create a POST request.                                                                                                                                          |
| [OAuthRequest](https://docs.servoy.com/reference/servoyextensions/server-plugins/oauth/oauthrequest)   | [createPutRequest(resourceURL)](#createputrequest-resourceurl)                    | Create a PUT request.                                                                                                                                           |
| [OAuthRequest](https://docs.servoy.com/reference/servoyextensions/server-plugins/oauth/oauthrequest)   | [createRequest(requestType, resourceURL)](#createrequest-requesttype-resourceurl) | Creates a JSOAuthRequest for with the enum of RequestType (GET, PUT, DELETE, etc) for a resource url.                                                           |
| [OAuthResponse](https://docs.servoy.com/reference/servoyextensions/server-plugins/oauth/oauthresponse) | [executeGetRequest(resourceURL)](#executegetrequest-resourceurl)                  | This is quick method by executing a GET request and returning right away the OAuthResponse So it would be the same as executeRequest(createRequest(RequestType. |
| [OAuthResponse](https://docs.servoy.com/reference/servoyextensions/server-plugins/oauth/oauthresponse) | [executeRequest(request)](#executerequest-request)                                | Method to execute requests that are made, and configured by #createRequest(Verb,String)                                                                         |
| [Number](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/number)                           | [getAccessExpiresIn()](#getaccessexpiresin)                                       | Returns the number of seconds left until the access token expires.                                                                                              |
| [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string)                           | [getAccessToken()](#getaccesstoken)                                               | Get the access token currently set on the service.                                                                                                              |
| [Number](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/number)                           | [getAccessTokenLifetime()](#getaccesstokenlifetime)                               | Return the token lifetime in seconds.                                                                                                                           |
| [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string)                           | [getAuthorizationURL()](#getauthorizationurl)                                     |                                                                                                                                                                 |
| [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string)                           | [getAuthorizationURL(params)](#getauthorizationurl-params)                        | Get the authorization url with some additional parameters.                                                                                                      |
| [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string)                           | [getIdToken()](#getidtoken)                                                       | Obtain the Openid token if it is available.                                                                                                                     |
| [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string)                           | [getRefreshToken()](#getrefreshtoken)                                             | Return the refresh token.                                                                                                                                       |
| [Boolean](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/boolean)                         | [isAccessTokenExpired()](#isaccesstokenexpired)                                   | Checks if the access token is expired.                                                                                                                          |
| [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string)                           | [refreshToken()](#refreshtoken)                                                   | Obtains a new access token if the OAuth api supports it.                                                                                                        |
| [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string)                           | [refreshToken(refreshToken, scope)](#refreshtoken-refreshtoken-scope)             | Obtains a new access token based on the refresh token, if the OAuth api supports it.                                                                            |
| void                                                                                                   | [revokeToken(token)](#revoketoken-token)                                          | Revoke the provided access token.                                                                                                                               |
| void                                                                                                   | [setAccessToken(code)](#setaccesstoken-code)                                      | Configure the oauth service with an access token using the scope that was initially set when creating the service.                                              |
| void                                                                                                   | [setAccessToken(code, scope)](#setaccesstoken-code-scope)                         | Configure the oauth service with an access token for the specified scope.                                                                                       |

## Methods Detailed

### createDeleteRequest(resourceURL)

Create a DELETE request.

**Parameters**

* [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) **resourceURL** the url of the resource to be deleted

**Returns:** [OAuthRequest](https://docs.servoy.com/reference/servoyextensions/server-plugins/oauth/oauthrequest) the request object

**Sample**

```js
var putRequest = service.createDeleteRequest("https://graph.microsoft.com/v1.0/me/drive/root:/FolderAA/FileBB.txt:/content");
var response = putRequest.execute();
if (response.getCode() == 204) {
		application.output("File was deleted "+response.getBody());
	}
else
{
		application.output('http status '+response.getCode());
		application.output("File could not be deleted: "+response.getBody())
}
```

### createGetRequest(resourceURL)

Create a GET request for a resource.

**Parameters**

* [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) **resourceURL** the url of the resource which you want to get

**Returns:** [OAuthRequest](https://docs.servoy.com/reference/servoyextensions/server-plugins/oauth/oauthrequest) the request object

**Sample**

```js
var getRequest = service.createGetRequest("https://api.linkedin.com/v2/me");
getRequest.addHeader("Accept", "application/json");

var response = getRequest.execute();
if (response.getCode() == 200) {
		var json = response.getAsJSON();
		application.output("Name is "+json.firstName);
	}
else
{
		application.output("ERROR http status "+response.getCode());
		application.output(response.getBody())
}
```

### createPostRequest(resourceURL)

Create a POST request.

**Parameters**

* [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) **resourceURL** the url where the enclosed entity will be stored

**Returns:** [OAuthRequest](https://docs.servoy.com/reference/servoyextensions/server-plugins/oauth/oauthrequest) the request object

**Sample**

```js
var postRequest = service.createPostRequest("https://.....");
postRequest.addHeader("Content-Type", "text/plain");
postRequest.addBodyParameter("param1", "value1");
var response = postRequest.execute();
```

### createPutRequest(resourceURL)

Create a PUT request.

**Parameters**

* [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) **resourceURL** the url where the enclosed entity will be stored

**Returns:** [OAuthRequest](https://docs.servoy.com/reference/servoyextensions/server-plugins/oauth/oauthrequest) the request object

**Sample**

```js
var putRequest = service.createPutRequest("https://graph.microsoft.com/v1.0/me/drive/root:/FolderAA/FileBB.txt:/content");
putRequest.addHeader("Content-Type", "text/plain");
putRequest.setPayload("ABC");
var response = putRequest.execute();
if (response.getCode() == 201) {
		application.output("New file was created "+response.getBody());
	}
else
{
		application.output("ERROR http status "+response.getCode());
		application.output("File could not be created: "+response.getBody())
}
```

### createRequest(requestType, resourceURL)

Creates a JSOAuthRequest for with the enum of RequestType (GET, PUT, DELETE, etc) for a resource url.

**Parameters**

* [enum](https://docs.servoy.com/reference/servoycore/dev-api/enum) **requestType** one of the types of plugins.oauth.RequestType
* [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) **resourceURL** the url of the resource you want to access

**Returns:** [OAuthRequest](https://docs.servoy.com/reference/servoyextensions/server-plugins/oauth/oauthrequest) a JSOAuthRequest object

**Sample**

```js
var request = service.createRequest(plugins.oauth.RequestType.GET, "https://api.linkedin.com/v2/me");
request.addHeader("Accept", "application/json");

var response = request.execute();
if (response.getCode() == 200) {
		var json = response.getAsJSON();
		application.output("Name is "+json.firstName);
	}
else
{
		application.output("ERROR http status "+response.getCode());
		application.output(response.getBody())
}
```

### executeGetRequest(resourceURL)

This is quick method by executing a GET request and returning right away the OAuthResponse So it would be the same as executeRequest(createRequest(RequestType.GET, url))

**Parameters**

* [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) **resourceURL** ;

**Returns:** [OAuthResponse](https://docs.servoy.com/reference/servoyextensions/server-plugins/oauth/oauthresponse) the OAuthResponse object

### executeRequest(request)

Method to execute requests that are made, and configured by #createRequest(Verb,String)

**Parameters**

* [OAuthRequest](https://docs.servoy.com/reference/servoyextensions/server-plugins/oauth/oauthrequest) **request** the JSOAuthRequest object that was created by #createRequest(Verb,String)

**Returns:** [OAuthResponse](https://docs.servoy.com/reference/servoyextensions/server-plugins/oauth/oauthresponse) the OAuthResponse object

**Sample**

```js
var request = service.createRequest(plugins.oauth.RequestType.GET, "https://api.linkedin.com/v2/me");
request.addHeader("Accept", "application/json");

var response = service.executeRequest(request);
if (response.getCode() == 200) {
		var json = response.getAsJSON();
		application.output("Name is "+json.firstName);
	}
else
{
		application.output("ERROR http status "+response.getCode());
		application.output(response.getBody())
}
```

### getAccessExpiresIn()

Returns the number of seconds left until the access token expires.

**Returns:** [Number](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/number) seconds left untol the access token expires.

**Sample**

```js
var seconds = service.getAccessExpiresIn();
 if (seconds < 60)
 {
 	application.output("The access token is going to expire in less than 1 minute! Use service.refreshToken() to get a new one");
 }
 else
 {
 	application.output("Make some requests");
 }
```

### getAccessToken()

Get the access token currently set on the service.

**Returns:** [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) the access token or null if it was not set

### getAccessTokenLifetime()

Return the token lifetime in seconds.

**Returns:** [Number](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/number) the token lifetime as it was retrieved by the OAuth provider with the access token

### getAuthorizationURL()

**Returns:** [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) The authorization URL for initiating the OAuth flow.

### getAuthorizationURL(params)

Get the authorization url with some additional parameters.

**Parameters**

* [Object](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/object) **params** a json containing the parameters and their values\
  &#x20;       e.g. {'param1': 'value1', 'param2': 'value2'}

**Returns:** [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) the authorization url with the provided parameters appended to the query string.

### getIdToken()

Obtain the Openid token if it is available.

**Returns:** [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) the id token, or null if was not set on the service.

### getRefreshToken()

Return the refresh token.

**Returns:** [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) the refresh token or null if it is not present

### isAccessTokenExpired()

Checks if the access token is expired. Returns false if the access token expire information is not set.

**Returns:** [Boolean](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/boolean) true if the access token is expired, false otherwise

### refreshToken()

Obtains a new access token if the OAuth api supports it.

**Returns:** [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) The new access token issued by the authorization server

**Sample**

```js
accessToken = service.refreshToken();
```

### refreshToken(refreshToken, scope)

Obtains a new access token based on the refresh token, if the OAuth api supports it.

**Parameters**

* [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) **refreshToken** the refresh token string
* [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) **scope** optional, if missing then the default scope configured on the service is used

**Returns:** [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) The new access token issued by the authorization server

**Sample**

```js
accessToken = service.refreshToken(theRefreshToken, scope);
```

### revokeToken(token)

Revoke the provided access token.

**Parameters**

* [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) **token** to revoke

**Returns:** void

### setAccessToken(code)

Configure the oauth service with an access token using the scope that was initially set when creating the service.

**Parameters**

* [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) **code** the authorization code used to request and access token

**Returns:** void

### setAccessToken(code, scope)

Configure the oauth service with an access token for the specified scope.

**Parameters**

* [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) **code** the authorization code used to request an access token
* [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) **scope** the scope for which to obtain an access token

**Returns:** void

***
