OAuth2.0

From Gcube Wiki
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

https://registry.d4science.org/icproxy/gcube/service/

Get authorization endpoint location in the following Table 1

Table 1: authorization endpoints location depending on the D4Science Gateway
D4Science Gateway name Authorization endpoint
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
EGIP Gateway https://egip.d4science.org/group/egip-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"?>
<serviceEndpoints>
   <Resource version="0.4.x">
      <ID>b1c5851f-1d47-4c60-8906-941ab859a334</ID>
      <Type>RuntimeResource</Type>
      <Scopes>
         <Scope>/gcube</Scope>
      </Scopes>
         ...
         <AccessPoint>
            <Description>AuthorisationServer where to authenticate external SmartGears services oAuth like</Description>
            <Interface>
               <Endpoint EntryName="AuthorisationServer">https://next.d4science.org/group/next/authorization</Endpoint>
            </Interface>
         </AccessPoint>
      </Profile>
   </Resource>
</serviceEndpoints>

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.

no

This is an example in development environment

https://next.d4science.org/group/next/authorization?client_id=ab9d32c9-9425-42f1-99d7-50d68e651e9c&scope=%2Fgcube&redirect_uri=https%3A%2F%2Fwww.gcube-system.org%2Fdevelopers&state=7d12bf13-111c-4f46-ab06-9e9e08ad377b

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

Oauth-ux.jpg

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 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.

yes
client_id the client identifier yes
client_secret the client_secret associated to the application yes

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
 
grant_type=authorization_code&code=...&redirect_uri=https%3A%2F%2Fwww.gcube-system.org%2Fdevelopers&client_id=ab9d32c9-9425-42f1-99d7-50d68e651e9c&client_secret=...

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.

Get the gcube-oauth endpoint location

The host to contact to perform this call can be again discovered via the icproxy service. This time the url will be something like

http://node10-d-d4s.d4science.org/icproxy/gcube/service/GCoreEndpoint/Portal/oauth?gcube-token=35eaf849-43d3-439c-a3bc-2f7c355c0f67

A resource profile is returned which contains the property jersey-servlet to be retrieved.

In development environment its current value is

http://socialnetworking-d-d4s.d4science.org/gcube-oauth/v2/access-token

In the production environment, its current value is

 https://socialnetworking1.d4science.org/gcube-oauth/v2/access-token

HTTP POST Example in JAVA

String ACCESS_TOKEN_ATTR = "access_token";
String SCOPE_ATTR = "scope";
String fullPath2oAuthService = "https://socialnetworking1.d4science.org/gcube-oauth/v2/access-token";
try {
				CloseableHttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
				HttpPost httpPostRequest = new HttpPost(fullPath2oAuthService);
				httpPostRequest.addHeader("Content-Type", "application/x-www-form-urlencoded");
				httpPostRequest.addHeader("gcube-token", client_secret); <--YOUR_CLIEND_SECRET is the client secret you received with the request for this 3rd party application
 
				List<NameValuePair> params = new ArrayList<NameValuePair>();
                                params.add(new BasicNameValuePair("grant_type", "authorization_code"));
                                params.add(new BasicNameValuePair("code", $YOUR_TEMP_CODE)); <--YOUR_TEMP_CODE is the authorization code you received from the previous step
                                params.add(new BasicNameValuePair("redirect_uri", "https://www.gcube-system.org/oauth-authentication-example/example-app"));  <-- The authorised redirect URI in your case 
                                params.add(new BasicNameValuePair("client_id", $YOUR_CLIEND_ID)); <--YOUR_CLIEND_ID is the clientid you received with the request for this 3rd party application 
                                params.add(new BasicNameValuePair("client_secret", $YOUR_CLIEND_SECRET)); <--YOUR_CLIEND_SECRET is the client secret you received with the request for this 3rd party application 
                                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");
				e.printStackTrace();
 
			}

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

/2/people/profile

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

{  
   success:true, // or false, if it failed for any reason
   message:null, // to be checked in case of errors
   result:{  
      roles:[  
          // roles in the access-token context
      ],
      avatar: .....,
      fullname: .....,
      username: .....
   }
}

See Also

Social Networking Service

Social Networking Service Docs SWAGGER