# oauth

(plugins.oauth)

## Overview

The `OAuth` plugin simplifies authentication and access to protected resources using OAuth protocols. It supports integration with predefined OAuth providers or custom APIs, enabling secure communication between applications and external services. Core functionalities include creating OAuth services, managing access tokens, and executing authenticated requests.

OAuth services can be configured through the `serviceBuilder`, which allows the definition of parameters such as client ID, client secret, scope, and state for secure sessions. The service builder also facilitates the integration of callback methods for handling responses. For more specific use cases, developers can build custom APIs by defining authorization and token endpoints, ensuring flexibility for various authentication workflows.

The plugin provides utility methods to streamline the process. It can generate redirect URLs for configuration on provider platforms and manage token extraction from responses. Once authenticated, OAuth services enable the execution of HTTP requests to protected endpoints, supporting various data formats such as JSON and binary. The plugin also facilitates error handling by capturing and relaying issues related to authentication or access requests.

By integrating the `OAuth` plugin, applications can securely authenticate users, access external APIs, and handle sensitive data interactions while adhering to modern security standards.

## **Returned Types**

[OAuthServiceBuilder](https://docs.servoy.com/reference/servoyextensions/server-plugins/oauth/oauthservicebuilder),[OAuthService](https://docs.servoy.com/reference/servoyextensions/server-plugins/oauth/oauthservice),[OAuthProviders](https://docs.servoy.com/reference/servoyextensions/server-plugins/oauth/oauthproviders),[OAuthResponseText](https://docs.servoy.com/reference/servoyextensions/server-plugins/oauth/oauthresponsetext),[OAuthResponseJSON](https://docs.servoy.com/reference/servoyextensions/server-plugins/oauth/oauthresponsejson),[OAuthResponseBinary](https://docs.servoy.com/reference/servoyextensions/server-plugins/oauth/oauthresponsebinary),[RequestType](https://docs.servoy.com/reference/servoyextensions/server-plugins/oauth/requesttype),[OAuthRequest](https://docs.servoy.com/reference/servoyextensions/server-plugins/oauth/oauthrequest),[OAuthTokenExtractors](https://docs.servoy.com/reference/servoyextensions/server-plugins/oauth/oauthtokenextractors),[ClientAuthentication](https://docs.servoy.com/reference/servoyextensions/server-plugins/oauth/clientauthentication),

## Methods Summarized

| Type                                                                                                               | Name                                                                                                                                                          | Summary                                                                                                  |
| ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| [CustomApiBuilder](https://docs.servoy.com/reference/servoyextensions/server-plugins/oauth/customapibuilder)       | [customApi(authorizationBaseUrl, accessTokenEndpoint)](#customapi-authorizationbaseurl-accesstokenendpoint)                                                   | Create a custom OAuth api builder.                                                                       |
| [OAuthService](https://docs.servoy.com/reference/servoyextensions/server-plugins/oauth/oauthservice)               | [getOAuthService(provider, clientId, clientSecret, scope, state, deeplinkmethod)](#getoauthservice-provider-clientid-clientsecret-scope-state-deeplinkmethod) | Creates an OAuth service that can be used to obtain an access token and access protected data.           |
| [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string)                                       | [getUsedRedirectUrl(builder)](#getusedredirecturl-builder)                                                                                                    | Help method to get the redirect URL which needs to be configured on the OAuth provider application page. |
| [OAuthServiceBuilder](https://docs.servoy.com/reference/servoyextensions/server-plugins/oauth/oauthservicebuilder) | [serviceBuilder(clientID)](#servicebuilder-clientid)                                                                                                          | Creates an OAuth service configurator.                                                                   |

## Methods Detailed

### customApi(authorizationBaseUrl, accessTokenEndpoint)

Create a custom OAuth api builder.

**Parameters**

* [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) **authorizationBaseUrl** the base URL where you should redirect your users to authenticate your application
* [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) **accessTokenEndpoint** the URL that receives the access token requests

**Returns:** [CustomApiBuilder](https://docs.servoy.com/reference/servoyextensions/server-plugins/oauth/customapibuilder) a custom API builder for OAuth.

**Sample**

```js
var customApi = plugins.oauth.customApi("https://example.com/oauth2/default/v1/authorize",  //authorization base url
                                        "https://example.com/oauth2/default/v1/token");     //access token endpoint
customApi = customApi.
plugins.oauth.serviceBuilder("0lqd1s0aw...")		//client/application ID
				.clientSecret("bIk6163KHi...")		//client secret
				.state("secret123337")				//anti forgery session state, required by the Facebook api
				.deeplink("deeplink_method")		//OPTIONAL deeplink method name or last part of your redirect URL, see docs
													//if missing, a global method with the name 'deeplink_svy_oauth' will be generated
				.callback(myFunction, 30) 			//see function below, timeout is 30 seconds
				.build(customApi);                  //the custom api created above

function myFunction(result, auth_outcome) {
if (result)
{
		//SUCCESS
		var service = auth_outcome;
		if (service.getAccessToken() == null) return;
		var response = service.executeGetRequest("https://graph.facebook.com/v2.11/me");
		if (response.getCode() == 200) {
			application.output(response.getBody());
			var json = response.getAsJSON();
			application.output("Name is "+json.name);
		}
		else {
			application.output('ERROR http status '+response.getCode());
		}
	else {
		//ERROR
		application.output("ERROR "+auth_outcome);//could not get access token, request timed out, etc..
	}
 }
}
```

### getOAuthService(provider, clientId, clientSecret, scope, state, deeplinkmethod)

Creates an OAuth service that can be used to obtain an access token and access protected data.\
This method will be deprecated in the following versions, the preferred way is plugins.oauth.serviceBuilder with a callback function.

**Parameters**

* [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) **provider** an OAuth provider id, see plugins.oauth.OAuthProviders
* [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) **clientId** your app id
* [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) **clientSecret** your client secret
* [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) **scope** configures the OAuth scope. This is only necessary in some APIs (like Microsoft's).
* [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) **state** configures the anti forgery session state. This is available in some APIs (like Facebook's).
* [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) **deeplinkmethod** the name of a global method, which will get the code returned by the OAuth provider

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

**Sample**

```js
var clientId = "";
var clientSecret = "";
var scope = null;
var state =  "secret123337";
var callback = "deeplink";
service = plugins.oauth.getOAuthService(plugins.oauth.OAuthProviders.FACEBOOK, clientId, clientSecret, null, state, callback, null)
application.showURL(service.getAuthorizationURL());

function deeplink(a,args) {
  service.setAccessToken(args.code);
  var response = service.executeGetRequest("https://graph.facebook.com/v2.11/me");
  if (response.getCode() == 200) {
  		 application.output(response.getBody());
  		 var json = response.getAsJSON();
  		 application.output("Name is "+json.name);
   }
  else {
    application.output('ERROR http status '+response.getCode());
    }
 }
```

### getUsedRedirectUrl(builder)

Help method to get the redirect URL which needs to be configured on the OAuth provider application page.\
The url is computed based on what is set on the service builder: deeplink method name, response mode and response type.

**Parameters**

* [OAuthServiceBuilder](https://docs.servoy.com/reference/servoyextensions/server-plugins/oauth/oauthservicebuilder) **builder** an OAuth service builder

**Returns:** [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) the redirect URL used by the OAuth service builder.

### serviceBuilder(clientID)

Creates an OAuth service configurator.

**Parameters**

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

**Returns:** [OAuthServiceBuilder](https://docs.servoy.com/reference/servoyextensions/server-plugins/oauth/oauthservicebuilder) an OAuth service builder object

**Sample**

```js
plugins.oauth.serviceBuilder("0lqd1s0aw...")		//client/application ID
				.clientSecret("bIk6163KHi...")		//client secret
				.defaultScope("email")				//ask permission to get the user email
				.state("secret123337")				//anti forgery session state, required by the Facebook api
				.deeplink("deeplink_method")		//OPTIONAL deeplink method name or last part of your redirect URL, see docs
													//if missing, a global method with the name 'deeplink_svy_oauth' will be generated
				.callback(myFunction, 30) 			//see function below, timeout is 30 seconds
				.build(plugins.oauth.OAuthProviders.FACEBOOK);

function myFunction(result, auth_outcome) {
if (result)
{
		//SUCCESS
		var service = auth_outcome;
		if (service.getAccessToken() == null) return;
		var response = service.executeGetRequest("https://graph.facebook.com/v2.11/me");
		if (response.getCode() == 200) {
			application.output(response.getBody());
			var json = response.getAsJSON();
			application.output("Name is "+json.name);
		}
		else {
			application.output('ERROR http status '+response.getCode());
		}
	else {
		//ERROR
		application.output("ERROR "+auth_outcome);//could not get access token, request timed out, etc..
	}
 }
}
```

***
