From Gcube Wiki
Revision as of 15:51, 26 July 2019 by Massimiliano.assante (Talk | contribs) (Get the gcube-oauth endpoint location)

Jump to: navigation, search

OAuth 2.0 gCube Support

By means of the OAuth 2.0 protocol (authorised) third party applications can operate on user's behalf over the D4Science infrastructure (while protecting the member's credentials). For more information about the OAuth authorization framework please visit the official OAuth site. For technical details you could also check the OAuth 2.0 RFC. In the following, the needed steps to authorize third party applications to operate on user's behalf and the D4Science infrastructure are explained.

Step 1 - Configure your application

Authorized third party applications must be registered on the Infrastructure. Up to now the application registration is not automatic but you need to open a ticket at https://support.d4science.org/projects/d4science.

The ticket needs to have 3rd Party Application Support as tracker. The application name as well as the redirect uri need to be provided (https is strongly suggested). This url must be absolute, and without arguments. Once the application is registered, it will have associated:

  • a unique client identifier (client_id);
  • a client secret which must be kept secret, as the name itself says (client_secret).
client_id: ab9d32c9-9425-42f1-99d7-50d68e651e9c
client_secret: y9r93zDv4D

Both are needed to proceed with the OAuth 2.0 workflow.

Step 2 - Require an authorization code

Once the application is registered and configured, an authorization code can be requested. This code is not the final one needed to perform operations on user behalf, but is the one that will be exchanged for that in the next step. To require this code that has a very short time to live, the application must invoke the authorization service, which is gateway dependant.

Retrieving the authorization endpoint location

The previous authorization endpoint location is portal's gateway dependant and can be found in Table 1 or retrieved dinamically by using the registry service REST-API hosted at


Get authorization endpoint location in the following Table 1

Table 1: authorization endpoints location depending on the D4Science Gateway
D4Science Gateway name Authorization endpoint
ARIADNEplus Gateway https://ariadne.d4science.org/group/ariadneplus-gateway/authorization
iMarine Gateway https://i-marine.d4science.org/group/imarine-gateway/authorization
AGINFRA+ Gateway https://aginfra.d4science.org/group/aginfra-gateway/authorization
BlueBRIDGE Gateway https://bluebridge.d4science.org/group/bluebridge-gateway/authorization
D4Science.org Gateway https://services.d4science.org/group/d4science-services-gateway/authorization
DESCRAMBLE Gateway https://descramble.d4science.org/group/descramble-gateway/authorization
GEMex Gateway https://gemex.d4science.org/group/gemex-gateway/authorization
OpenAIRE-Connect Gateway https://openaire-connect.d4science.org/group/openaire-connect-gateway/authorization
PARTHENOS Gateway https://parthenos.d4science.org/group/parthenos-gateway/authorization
SoBigData Gateway https://sobigdata.d4science.org/group/sobigdata-gateway/authorization

Retrieve the authorization endpoint location dynamically (ADVANCED MODE)

Registry Swagger REST-API avaiable at: https://dev.d4science.org/swagger/registry/

Which requires an authorization token. The returned profile is something like

<?xml version="1.0" encoding="UTF-8"?>
   <Resource version="0.4.x">
            <Description>AuthorisationServer where to authenticate external SmartGears services oAuth like</Description>
               <Endpoint EntryName="AuthorisationServer">https://next.d4science.org/group/next/authorization</Endpoint>

Invoking the authorization service

Once you got the AuthorisationServer endpoint and the call is executed, two things can happen:

  • the user is requested to perform the login, thus accepting the application operation and granting it;
  • if there is a valid existing permission grant for the application, the login operation is by-passed and the redirect_uri is followed.

The request is an HTTP GET call, that needs the following parameters to be provided

Parameter Description Required
client_id the client identifier associated to the application yes
redirect_uri the redirect uri provided at registration phase yes
state a unique string value hard to guess, needed to prevent CRSF attacks (e.g. AAedBEeF545sdfKef897) yes
scope this field is optional. It can be specified to request (with the next step) an access token valid for a given

infrastructure scope. If missing, the scope will be choose by the user on credentials insertion.


This is an example in development environment


End user Experience

Once redirected, the user will be presented with D4Science's authentication dialog box. This identifies your application as well as outlines the particular member permissions that your application requests. The logo and application name can be configurable, in the example the application name is Application X


Application is Accepted

If the user grants permissions to the application, a redirection to the redirect_uri is performed. Attached to the redirect_uri, two important url arguments are provided

  • code: which is the authorization code. It expires in 10 seconds;
  • state: which is the same value provided by the application, which is in charge of checking that it is the same.

Application is Rejected

If, for any reason, the request fails, the redirect_uri is still followed but the url has attached the following parameters

  • error: a code that states the type of error;
  • error_description: a textual description of the actual error;
  • state: which is the same value provided by the application, which is in charge of checking that it is the same.

Step 3 - Exchange Authorization Code for an Access Token

This is the step in which the previously obtained code can be exchanged to obtain a real access token. This time, an HTTP POST method needs to be performed, with a Content-Type of type application/x-www-form-urlencoded.

The client_id and secret must be passed as the basic auth header Base64 encoded, see the example in Java below:


String idAndSecret = new StringBuilder(client_id).append(":").append(client_secret).toString();
String encodingIdAndSecret = Base64.getEncoder().encodeToString(idAndSecret.getBytes(StandardCharsets.UTF_8));
httpPostRequest.setHeader("Authorization", "Basic " + encodingIdAndSecret);

The request-body must contain the following parameters:

Parameter Description Required
grant_type The value of this field should always be authorization_code yes
code the authorization code you received from the previous step. yes
redirect_uri the same 'redirect_uri' value that you

passed in the previous step.


For instance, in development environment

POST /gcube-oauth/v2/access-token HTTP/1.1
Host: socialnetworking-d-d4s.d4science.org
Content-Type: application/x-www-form-urlencoded

In case of success, the response will contain a JSON object, having these properties:

  • access_token: the obtained access token to use to perform operations on user's behalf;
  • expires_in: the time to live of the token expressed in seconds;
  • scope: in which scope the token is valid;
  • token_type: that is "Bearer".

In case of failures, instead, the returned object will contain:

  • error : an error string according the oauth 2.0 RFC.
  • error_description : a text description for the error.

D4Science oAuth2 endpoint location

In the production environment, its value is



String ACCESS_TOKEN_ATTR = "access_token";
String SCOPE_ATTR = "scope";
String fullPath2oAuthService = "https://api.d4science.org/oauth/v2/access-token";
try {
		CloseableHttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
		HttpPost httpPostRequest = new HttpPost(fullPath2oAuthService);
		String idAndSecret = new StringBuilder(client_id).append(":").append(client_secret).toString();
		String encodingIdAndSecret = Base64.getEncoder().encodeToString(idAndSecret.getBytes(StandardCharsets.UTF_8));
		httpPostRequest.setHeader("Authorization", "Basic " + encodingIdAndSecret);
		httpPostRequest.addHeader("Content-Type", "application/x-www-form-urlencoded");
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("grant_type", "authorization_code"));
		params.add(new BasicNameValuePair("code", tempCode));
		params.add(new BasicNameValuePair("redirect_uri", "https://www.gcube-system.org/oauth-authentication-example/example-app"));
		httpPostRequest.setEntity(new UrlEncodedFormEntity(params));
		CloseableHttpResponse httpresponse = httpClient.execute(httpPostRequest);
		int responseCode = httpresponse.getStatusLine().getStatusCode();
		if (responseCode < 200 || responseCode >= 300) {
			System.out.println("Error while getting authorization code, response status line from "
							+ fullPath2oAuthService + " was: " + responseCode);	
		JSONParser parser = new JSONParser();
		JSONObject json = (JSONObject) parser.parse(EntityUtils.toString(httpresponse.getEntity()));
		accessToken = json.get(ACCESS_TOKEN_ATTR).toString();
		scope = json.get(SCOPE_ATTR).toString();
	} catch(Exception e){
		System.out.println("Failed to perform request");

Step 4 - Get member data

Having an access token, your application can perform some operations on behalf of the user. For instance, it can retrieve user's information profile by exploiting the social networking web service.

Its current production endpoint is: https://socialnetworking1.d4science.org/social-networking-library-ws/rest/

The subservice to call, once the social networking service endpoint has been retrieved, is this one


It requires a gcube-token as query parameter, whose value is exactly the access token retrieved in the previous step. The result is something like this

id: ".....",
roles: [ ],     // roles in the given-token context, e.g. VRE-Manager
picture: "....",
name: "....",
middle_name: "....",
male: as boolean ,
location_industry: "....",
given_name: "....",
email: "....",
job_title: "....",
family_name: "....",
verified_email: as boolean 

See Also

Social Networking Service

Social Networking Service Docs SWAGGER