Difference between revisions of "OAuth2.0"

From Gcube Wiki
Jump to: navigation, search
(Step 4 - Get member data)
(Step 4 - Get member data)
Line 277: Line 277:
 
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
 
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
  
<source lang="son">
+
<source lang="json">
 
{
 
{
 
id: ".....",
 
id: ".....",

Revision as of 11:25, 5 April 2019

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
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"?>
<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 client_id and secret must be passed as the basic auth header Base64 encoded, see the example in Java below:

e.g.

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

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);
		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");
		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/users/get-oauth-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

Invalid language.

You need to specify a language like this: <source lang="html4strict">...</source>

Supported languages for syntax highlighting:

4cs, 6502acme, 6502kickass, 6502tasm, 68000devpac, abap, actionscript, actionscript3, ada, aimms, algol68, apache, applescript, arm, asm, asp, asymptote, autoconf, autohotkey, autoit, avisynth, awk, bascomavr, bash, basic4gl, bf, bibtex, blitzbasic, bnf, boo, c, caddcl, cadlisp, cfdg, cfm, chaiscript, chapel, cil, clojure, cmake, cobol, coffeescript, cpp, csharp, css, cuesheet, d, dart, dcl, dcpu16, dcs, delphi, diff, div, dos, dot, e, ecmascript, eiffel, email, epc, erlang, euphoria, ezt, f1, falcon, fo, fortran, freebasic, freeswitch, fsharp, gambas, gdb, genero, genie, gettext, glsl, gml, gnuplot, go, groovy, gwbasic, haskell, haxe, hicest, hq9plus, html4strict, html5, icon, idl, ini, inno, intercal, io, ispfpanel, j, java, java5, javascript, jcl, jquery, kixtart, klonec, klonecpp, latex, lb, ldif, lisp, llvm, locobasic, logtalk, lolcode, lotusformulas, lotusscript, lscript, lsl2, lua, m68k, magiksf, make, mapbasic, matlab, mirc, mmix, modula2, modula3, mpasm, mxml, mysql, nagios, netrexx, newlisp, nginx, nimrod, nsis, oberon2, objc, objeck, ocaml, octave, oobas, oorexx, oracle11, oracle8, oxygene, oz, parasail, parigp, pascal, pcre, per, perl, perl6, pf, php, pic16, pike, pixelbender, pli, plsql, postgresql, postscript, povray, powerbuilder, powershell, proftpd, progress, prolog, properties, providex, purebasic, pycon, pys60, python, q, qbasic, qml, racket, rails, rbs, rebol, reg, rexx, robots, rpmspec, rsplus, ruby, rust, sas, scala, scheme, scilab, scl, sdlbasic, smalltalk, smarty, spark, sparql, sql, standardml, stonescript, systemverilog, tcl, teraterm, text, thinbasic, tsql, typoscript, unicon, upc, urbi, uscript, vala, vb, vbnet, vbscript, vedit, verilog, vhdl, vim, visualfoxpro, visualprolog, whitespace, whois, winbatch, xbasic, xml, xpp, yaml, z80, zxbasic


{
id: ".....",
roles: [ ],
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