Feature #17265, Provide oAuth2 service with capability to be deployed on

a multi instance cluster by using Memcached
This commit is contained in:
Massimiliano Assante 2019-08-21 09:46:15 +02:00
parent aba6e21693
commit 316bd0a7fa
6 changed files with 59 additions and 61 deletions

View File

@ -6,15 +6,11 @@
<attribute name="maven.pomderived" value="true"/> <attribute name="maven.pomderived" value="true"/>
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java"> <classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes> <attributes>
<attribute name="optional" value="true"/> <attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/> <attribute name="maven.pomderived" value="true"/>
<attribute name="test" value="true"/>
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER"> <classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">

View File

@ -5,4 +5,5 @@ org.eclipse.jdt.core.compiler.compliance=1.7
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.release=disabled
org.eclipse.jdt.core.compiler.source=1.7 org.eclipse.jdt.core.compiler.source=1.7

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0"> <?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
<wb-module deploy-name="oauth"> <wb-module deploy-name="gcube-oauth">
<wb-resource deploy-path="/" source-path="/target/m2e-wtp/web-resources"/> <wb-resource deploy-path="/" source-path="/target/m2e-wtp/web-resources"/>
<wb-resource deploy-path="/" source-path="/src/main/webapp" tag="defaultRootSource"/> <wb-resource deploy-path="/" source-path="/src/main/webapp" tag="defaultRootSource"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/java"/> <wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/java"/>

12
pom.xml
View File

@ -1,4 +1,5 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
@ -12,11 +13,11 @@
<groupId>org.gcube.portal</groupId> <groupId>org.gcube.portal</groupId>
<artifactId>oauth</artifactId> <artifactId>oauth</artifactId>
<packaging>war</packaging> <packaging>war</packaging>
<version>1.0.1-SNAPSHOT</version> <version>1.1.0-SNAPSHOT</version>
<name>gcube-oauth</name> <name>gcube-oauth</name>
<properties> <properties>
<java-version>1.7</java-version> <java-version>1.8</java-version>
<version.jersey>2.22.1</version.jersey> <version.jersey>2.22.1</version.jersey>
<distroDirectory>${project.basedir}/distro</distroDirectory> <distroDirectory>${project.basedir}/distro</distroDirectory>
<webappDirectory>${project.build.directory}/${project.build.finalName}</webappDirectory> <webappDirectory>${project.build.directory}/${project.build.finalName}</webappDirectory>
@ -44,6 +45,11 @@
</dependencyManagement> </dependencyManagement>
<dependencies> <dependencies>
<dependency>
<groupId>net.spy</groupId>
<artifactId>spymemcached</artifactId>
<version>2.12.3</version>
</dependency>
<dependency> <dependency>
<groupId>org.glassfish.jersey.containers</groupId> <groupId>org.glassfish.jersey.containers</groupId>
<!-- if your container implements Servlet API older than 3.0, use "jersey-container-servlet-core" --> <!-- if your container implements Servlet API older than 3.0, use "jersey-container-servlet-core" -->

View File

@ -2,9 +2,8 @@ package org.gcube.portal.oauth;
import static org.gcube.common.authorization.client.Constants.authorizationService; import static org.gcube.common.authorization.client.Constants.authorizationService;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.inject.Singleton; import javax.inject.Singleton;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
@ -26,13 +25,13 @@ import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.authorization.library.utils.Caller; import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.common.scope.api.ScopeProvider; import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.portal.oauth.cache.CacheBean; import org.gcube.portal.oauth.cache.CacheBean;
import org.gcube.portal.oauth.cache.CacheCleaner;
import org.gcube.portal.oauth.input.PushCodeBean; import org.gcube.portal.oauth.input.PushCodeBean;
import org.gcube.portal.oauth.output.AccessTokenBeanResponse; import org.gcube.portal.oauth.output.AccessTokenBeanResponse;
import org.gcube.portal.oauth.output.AccessTokenErrorResponse; import org.gcube.portal.oauth.output.AccessTokenErrorResponse;
import org.gcube.smartgears.Constants;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import net.spy.memcached.MemcachedClient;
@Path("/v2") @Path("/v2")
@Singleton @Singleton
@ -40,21 +39,18 @@ public class OauthService {
public static final String OAUTH_TOKEN_GET_METHOD_NAME_REQUEST = "access-token"; public static final String OAUTH_TOKEN_GET_METHOD_NAME_REQUEST = "access-token";
private static final String GRANT_TYPE_VALUE = "authorization_code"; private static final String GRANT_TYPE_VALUE = "authorization_code";
private static final String AUTHORIZATION_HEADER = "Authorization"; private static final String AUTHORIZATION_HEADER = "Authorization";
private static final int CACHE_SECONDS_EXPIRATION = 10;
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(OauthService.class); private static final org.slf4j.Logger logger = LoggerFactory.getLogger(OauthService.class);
/** /**
* This map contains couples <code, {qualifier-token, insert time, scope, redirect uri, client id}> * This map contains couples <code, {qualifier-token, insert time, scope, redirect uri, client id}>
*/ */
private Map<String, CacheBean> entries; private MemcachedClient entries;
/**
* Cleaner thread
*/
CacheCleaner cleaner;
/** /**
* Since this is a singleton sub-service, there will be just one call to this constructor and one running thread * Since this is a singleton sub-service, there will be just one call to this constructor and one running thread
@ -62,15 +58,12 @@ public class OauthService {
*/ */
public OauthService() { public OauthService() {
logger.info("Singleton gcube-oauth service built."); logger.info("Singleton gcube-oauth service built.");
entries = new ConcurrentHashMap<String, CacheBean>(); entries = DistributedCacheClient.getInstance().getMemcachedClient();
cleaner = new CacheCleaner(entries);
cleaner.start();
} }
@Override @Override
protected void finalize(){ protected void finalize(){
if(cleaner != null) entries.shutdown();
cleaner.interrupt();
} }
/** /**
@ -106,12 +99,14 @@ public class OauthService {
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Path("push-authentication-code") @Path("push-authentication-code")
/** /**
* CALLED FROM THE PORTAL PORTLET to pass among the other the temp code which expires in 10 seconds
*
* The portal will push a qualified token together a code * The portal will push a qualified token together a code
* @return Response with status 201 if the code has been saved correctly * @return Response with status 201 if the code has been saved correctly
*/ */
public Response pushAuthCode(PushCodeBean bean) { public Response pushAuthCode(PushCodeBean bean) {
logger.info("Request to push "); logger.info("Request to push aothCode from the portal ");
Caller caller = AuthorizationProvider.instance.get(); Caller caller = AuthorizationProvider.instance.get();
String token = SecurityTokenProvider.instance.get(); String token = SecurityTokenProvider.instance.get();
@ -141,7 +136,7 @@ public class OauthService {
entity("{\"error\"=\"'redirect_uri' cannot be null or missing\"").build(); entity("{\"error\"=\"'redirect_uri' cannot be null or missing\"").build();
logger.info("Saving entry defined by " + bean + " in cache, token is " + token.substring(0, 10) + "***************"); logger.info("Saving entry defined by " + bean + " in cache, token is " + token.substring(0, 10) + "***************");
entries.put(code, new CacheBean(token, ScopeProvider.instance.get(), redirectUri, clientId, System.currentTimeMillis())); entries.set(code, CACHE_SECONDS_EXPIRATION, new CacheBean(token, ScopeProvider.instance.get(), redirectUri, clientId));
return Response.status(status).build(); return Response.status(status).build();
} }
@ -194,8 +189,8 @@ public class OauthService {
return Response.status(status).entity(new AccessTokenErrorResponse(errorMessage, null)).build(); return Response.status(status).entity(new AccessTokenErrorResponse(errorMessage, null)).build();
}else{ }else{
logger.info("The request is ok"); logger.info("The request is ok");
String tokenToReturn = entries.get(code).getToken(); String tokenToReturn = ((CacheBean) entries.get(code)).getToken();
String scope = entries.get(code).getScope(); String scope = ((CacheBean)entries.get(code)).getScope();
status = Status.OK; status = Status.OK;
return Response.status(status).entity(new AccessTokenBeanResponse(tokenToReturn, scope)).build(); return Response.status(status).entity(new AccessTokenBeanResponse(tokenToReturn, scope)).build();
} }
@ -212,8 +207,15 @@ public class OauthService {
String credentials = new String(DatatypeConverter.parseBase64Binary(base64Credentials)); String credentials = new String(DatatypeConverter.parseBase64Binary(base64Credentials));
// credentials = username:password // credentials = username:password
String[] splitCreds = credentials.split(":"); String[] splitCreds = credentials.split(":");
String clientId = URLDecoder.decode(splitCreds[0]); String clientId = null;
String clientSecret = URLDecoder.decode(splitCreds[1]); String clientSecret = null;
try {
clientId = URLDecoder.decode(splitCreds[0], java.nio.charset.StandardCharsets.UTF_8.toString());
clientSecret = URLDecoder.decode(splitCreds[1], java.nio.charset.StandardCharsets.UTF_8.toString());
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new CredentialsBean(clientId, clientSecret); return new CredentialsBean(clientId, clientSecret);
} }
@ -236,9 +238,9 @@ public class OauthService {
return "invalid_request"; return "invalid_request";
if(!checkIsapplicationTokenType(authorizationService().get(credentials.getClientSecret()).getClientInfo().getType())) // it is not an app token or it is not a token if(!checkIsapplicationTokenType(authorizationService().get(credentials.getClientSecret()).getClientInfo().getType())) // it is not an app token or it is not a token
return "invalid_client"; return "invalid_client";
if(!entries.containsKey(code) || CacheBean.isExpired(entries.get(code))) if(entries.get(code) == null)
return "invalid_grant"; return "invalid_grant";
CacheBean entry = entries.get(code); CacheBean entry = (CacheBean) entries.get(code);
if(!entry.getRedirectUri().equals(redirectUri) || !entry.getClientId().equals(credentials.getClientId())) if(!entry.getRedirectUri().equals(redirectUri) || !entry.getClientId().equals(credentials.getClientId()))
return "invalid_grant"; return "invalid_grant";
if(!grantType.equals(GRANT_TYPE_VALUE)) if(!grantType.equals(GRANT_TYPE_VALUE))

View File

@ -1,19 +1,25 @@
package org.gcube.portal.oauth.cache; package org.gcube.portal.oauth.cache;
import java.io.Serializable;
/** /**
* A cache bean object for oauth support * A cache bean object for oauth support
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
* @author Massimiliano Assante, National Research Council of Italy (CNR) - ISTI
*/ */
public class CacheBean { @SuppressWarnings("serial")
public class CacheBean implements Serializable {
private String token; private String token;
private String scope; private String scope;
private String redirectUri; private String redirectUri;
private String clientId; private String clientId;
private Long insertTime;
private static final int TOKEN_TTL = 1000 * 10;
public CacheBean() {
super();
}
/** /**
* @param token * @param token
* @param scope * @param scope
@ -21,14 +27,12 @@ public class CacheBean {
* @param clientId * @param clientId
* @param insertTime * @param insertTime
*/ */
public CacheBean(String token, String scope, String redirectUri, public CacheBean(String token, String scope, String redirectUri, String clientId) {
String clientId, Long insertTime) {
super(); super();
this.token = token; this.token = token;
this.scope = scope; this.scope = scope;
this.redirectUri = redirectUri; this.redirectUri = redirectUri;
this.clientId = clientId; this.clientId = clientId;
this.insertTime = insertTime;
} }
public String getScope() { public String getScope() {
@ -47,14 +51,6 @@ public class CacheBean {
this.token = token; this.token = token;
} }
public Long getInsertTime() {
return insertTime;
}
public void setInsertTime(Long insertTime) {
this.insertTime = insertTime;
}
public String getRedirectUri() { public String getRedirectUri() {
return redirectUri; return redirectUri;
} }
@ -73,19 +69,16 @@ public class CacheBean {
@Override @Override
public String toString() { public String toString() {
return "CacheBean [token=" + token + ", scope=" + scope StringBuilder builder = new StringBuilder();
+ ", redirectUri=" + redirectUri + ", clientId=" + clientId builder.append("CacheBean [token=");
+ ", insertTime=" + insertTime + "]"; builder.append(token);
} builder.append(", scope=");
builder.append(scope);
/** builder.append(", redirectUri=");
* True if the code expired, false otherwise builder.append(redirectUri);
* @return builder.append(", clientId=");
*/ builder.append(clientId);
public static boolean isExpired(CacheBean bean){ builder.append("]");
return builder.toString();
return System.currentTimeMillis() > TOKEN_TTL + bean.insertTime; }
}
} }