Compare commits
2 Commits
aba6e21693
...
f1d8489760
Author | SHA1 | Date |
---|---|---|
Massimiliano Assante | f1d8489760 | |
Massimiliano Assante | 316bd0a7fa |
|
@ -6,15 +6,11 @@
|
|||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</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">
|
||||
<attributes>
|
||||
<attribute name="optional" value="true"/>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
<attribute name="test" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
/target/
|
|
@ -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.enumIdentifier=error
|
||||
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
|
||||
org.eclipse.jdt.core.compiler.release=disabled
|
||||
org.eclipse.jdt.core.compiler.source=1.7
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
<?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="/src/main/webapp" tag="defaultRootSource"/>
|
||||
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/java"/>
|
||||
|
|
12
pom.xml
12
pom.xml
|
@ -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">
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
@ -12,11 +13,11 @@
|
|||
<groupId>org.gcube.portal</groupId>
|
||||
<artifactId>oauth</artifactId>
|
||||
<packaging>war</packaging>
|
||||
<version>1.0.1-SNAPSHOT</version>
|
||||
<version>1.1.0-SNAPSHOT</version>
|
||||
<name>gcube-oauth</name>
|
||||
|
||||
<properties>
|
||||
<java-version>1.7</java-version>
|
||||
<java-version>1.8</java-version>
|
||||
<version.jersey>2.22.1</version.jersey>
|
||||
<distroDirectory>${project.basedir}/distro</distroDirectory>
|
||||
<webappDirectory>${project.build.directory}/${project.build.finalName}</webappDirectory>
|
||||
|
@ -44,6 +45,11 @@
|
|||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>net.spy</groupId>
|
||||
<artifactId>spymemcached</artifactId>
|
||||
<version>2.12.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.containers</groupId>
|
||||
<!-- if your container implements Servlet API older than 3.0, use "jersey-container-servlet-core" -->
|
||||
|
|
|
@ -0,0 +1,109 @@
|
|||
package org.gcube.portal.oauth;
|
||||
|
||||
import static org.gcube.resources.discovery.icclient.ICFactory.clientFor;
|
||||
import static org.gcube.resources.discovery.icclient.ICFactory.queryFor;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.gcube.common.resources.gcore.ServiceEndpoint;
|
||||
import org.gcube.common.resources.gcore.ServiceEndpoint.AccessPoint;
|
||||
import org.gcube.common.resources.gcore.utils.Group;
|
||||
import org.gcube.common.scope.api.ScopeProvider;
|
||||
import org.gcube.resources.discovery.client.api.DiscoveryClient;
|
||||
import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
|
||||
import org.gcube.smartgears.ContextProvider;
|
||||
import org.gcube.smartgears.context.application.ApplicationContext;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import net.spy.memcached.MemcachedClient;
|
||||
|
||||
/**
|
||||
* @author Massimiliano Assante at ISTI-CNR
|
||||
*/
|
||||
public class DistributedCacheClient {
|
||||
|
||||
// Logger
|
||||
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(DistributedCacheClient.class);
|
||||
|
||||
private static final String MEMCACHED_RESOURCE_NAME = "Memcached";
|
||||
private static final String CATEGORY = "Database";
|
||||
|
||||
private MemcachedClient mClient;
|
||||
|
||||
/**
|
||||
* Singleton object
|
||||
*/
|
||||
private static DistributedCacheClient singleton = new DistributedCacheClient();
|
||||
|
||||
/**
|
||||
* Build the singleton instance
|
||||
*/
|
||||
private DistributedCacheClient(){
|
||||
List<InetSocketAddress> addrs = discoverHostOfServiceEndpoint();
|
||||
try {
|
||||
mClient = new MemcachedClient(addrs);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the singleton instance
|
||||
*/
|
||||
public static DistributedCacheClient getInstance(){
|
||||
if (singleton == null) {
|
||||
singleton = new DistributedCacheClient();
|
||||
}
|
||||
return singleton;
|
||||
}
|
||||
|
||||
public MemcachedClient getMemcachedClient() {
|
||||
return mClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve endpoint resoruce from IS
|
||||
* @return List of InetSocketAddresses
|
||||
* @throws Exception
|
||||
*/
|
||||
private static List<InetSocketAddress> discoverHostOfServiceEndpoint(){
|
||||
|
||||
String currentScope = ScopeProvider.instance.get();
|
||||
ApplicationContext ctx = ContextProvider.get(); // get this info from SmartGears
|
||||
String infrastructure = "/"+ctx.container().configuration().infrastructure();
|
||||
ScopeProvider.instance.set(infrastructure);
|
||||
List<InetSocketAddress> toReturn = new ArrayList<InetSocketAddress>();
|
||||
try{
|
||||
SimpleQuery query = queryFor(ServiceEndpoint.class);
|
||||
query.addCondition("$resource/Profile/Name/text() eq '"+ MEMCACHED_RESOURCE_NAME +"'");
|
||||
query.addCondition("$resource/Profile/Category/text() eq '"+ CATEGORY +"'");
|
||||
DiscoveryClient<ServiceEndpoint> client = clientFor(ServiceEndpoint.class);
|
||||
List<ServiceEndpoint> ses = client.submit(query);
|
||||
if (ses.isEmpty()) {
|
||||
logger.error("There is no Memcached cluster having name: " + MEMCACHED_RESOURCE_NAME + " and Category " + CATEGORY + " on root context in this infrastructure: ");
|
||||
return null;
|
||||
}
|
||||
for (ServiceEndpoint se : ses) {
|
||||
Group<AccessPoint> aps = se.profile().accessPoints();
|
||||
for (AccessPoint ap : aps.asCollection()) {
|
||||
String address = ap.address(); //e.g. socialnetworking-d-d4s.d4science.org:11211
|
||||
String[] splits = address.split(":");
|
||||
String hostname = splits[0];
|
||||
int port = Integer.parseInt(splits[1]);
|
||||
toReturn.add(new InetSocketAddress(hostname, port));
|
||||
}
|
||||
break;
|
||||
}
|
||||
} catch(Exception e){
|
||||
logger.error("Error while retrieving hosts for the Memcached cluster having name: " + MEMCACHED_RESOURCE_NAME + " and Category " + CATEGORY + " on root context");
|
||||
}finally{
|
||||
ScopeProvider.instance.set(currentScope);
|
||||
}
|
||||
ScopeProvider.instance.set(currentScope);
|
||||
return toReturn;
|
||||
}
|
||||
|
||||
}
|
|
@ -2,9 +2,8 @@ package org.gcube.portal.oauth;
|
|||
|
||||
import static org.gcube.common.authorization.client.Constants.authorizationService;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLDecoder;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import javax.inject.Singleton;
|
||||
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.scope.api.ScopeProvider;
|
||||
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.output.AccessTokenBeanResponse;
|
||||
import org.gcube.portal.oauth.output.AccessTokenErrorResponse;
|
||||
import org.gcube.smartgears.Constants;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import net.spy.memcached.MemcachedClient;
|
||||
|
||||
|
||||
@Path("/v2")
|
||||
@Singleton
|
||||
|
@ -40,21 +39,18 @@ public class OauthService {
|
|||
|
||||
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 AUTHORIZATION_HEADER = "Authorization";
|
||||
|
||||
private static final int CACHE_SECONDS_EXPIRATION = 10;
|
||||
|
||||
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}>
|
||||
*/
|
||||
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
|
||||
|
@ -62,15 +58,12 @@ public class OauthService {
|
|||
*/
|
||||
public OauthService() {
|
||||
logger.info("Singleton gcube-oauth service built.");
|
||||
entries = new ConcurrentHashMap<String, CacheBean>();
|
||||
cleaner = new CacheCleaner(entries);
|
||||
cleaner.start();
|
||||
entries = DistributedCacheClient.getInstance().getMemcachedClient();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void finalize(){
|
||||
if(cleaner != null)
|
||||
cleaner.interrupt();
|
||||
entries.shutdown();
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -106,12 +99,14 @@ public class OauthService {
|
|||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@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
|
||||
* @return Response with status 201 if the code has been saved correctly
|
||||
*/
|
||||
public Response pushAuthCode(PushCodeBean bean) {
|
||||
|
||||
logger.info("Request to push ");
|
||||
logger.info("Request to push aothCode from the portal ");
|
||||
|
||||
Caller caller = AuthorizationProvider.instance.get();
|
||||
String token = SecurityTokenProvider.instance.get();
|
||||
|
@ -141,7 +136,7 @@ public class OauthService {
|
|||
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) + "***************");
|
||||
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();
|
||||
}
|
||||
|
||||
|
@ -194,8 +189,8 @@ public class OauthService {
|
|||
return Response.status(status).entity(new AccessTokenErrorResponse(errorMessage, null)).build();
|
||||
}else{
|
||||
logger.info("The request is ok");
|
||||
String tokenToReturn = entries.get(code).getToken();
|
||||
String scope = entries.get(code).getScope();
|
||||
String tokenToReturn = ((CacheBean) entries.get(code)).getToken();
|
||||
String scope = ((CacheBean)entries.get(code)).getScope();
|
||||
status = Status.OK;
|
||||
return Response.status(status).entity(new AccessTokenBeanResponse(tokenToReturn, scope)).build();
|
||||
}
|
||||
|
@ -212,8 +207,15 @@ public class OauthService {
|
|||
String credentials = new String(DatatypeConverter.parseBase64Binary(base64Credentials));
|
||||
// credentials = username:password
|
||||
String[] splitCreds = credentials.split(":");
|
||||
String clientId = URLDecoder.decode(splitCreds[0]);
|
||||
String clientSecret = URLDecoder.decode(splitCreds[1]);
|
||||
String clientId = null;
|
||||
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);
|
||||
|
||||
}
|
||||
|
@ -236,9 +238,9 @@ public class OauthService {
|
|||
return "invalid_request";
|
||||
if(!checkIsapplicationTokenType(authorizationService().get(credentials.getClientSecret()).getClientInfo().getType())) // it is not an app token or it is not a token
|
||||
return "invalid_client";
|
||||
if(!entries.containsKey(code) || CacheBean.isExpired(entries.get(code)))
|
||||
if(entries.get(code) == null)
|
||||
return "invalid_grant";
|
||||
CacheBean entry = entries.get(code);
|
||||
CacheBean entry = (CacheBean) entries.get(code);
|
||||
if(!entry.getRedirectUri().equals(redirectUri) || !entry.getClientId().equals(credentials.getClientId()))
|
||||
return "invalid_grant";
|
||||
if(!grantType.equals(GRANT_TYPE_VALUE))
|
||||
|
|
|
@ -1,19 +1,25 @@
|
|||
package org.gcube.portal.oauth.cache;
|
||||
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* A cache bean object for oauth support
|
||||
* @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 scope;
|
||||
private String redirectUri;
|
||||
private String clientId;
|
||||
private Long insertTime;
|
||||
private static final int TOKEN_TTL = 1000 * 10;
|
||||
|
||||
public CacheBean() {
|
||||
super();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param token
|
||||
* @param scope
|
||||
|
@ -21,14 +27,12 @@ public class CacheBean {
|
|||
* @param clientId
|
||||
* @param insertTime
|
||||
*/
|
||||
public CacheBean(String token, String scope, String redirectUri,
|
||||
String clientId, Long insertTime) {
|
||||
public CacheBean(String token, String scope, String redirectUri, String clientId) {
|
||||
super();
|
||||
this.token = token;
|
||||
this.scope = scope;
|
||||
this.redirectUri = redirectUri;
|
||||
this.clientId = clientId;
|
||||
this.insertTime = insertTime;
|
||||
}
|
||||
|
||||
public String getScope() {
|
||||
|
@ -47,14 +51,6 @@ public class CacheBean {
|
|||
this.token = token;
|
||||
}
|
||||
|
||||
public Long getInsertTime() {
|
||||
return insertTime;
|
||||
}
|
||||
|
||||
public void setInsertTime(Long insertTime) {
|
||||
this.insertTime = insertTime;
|
||||
}
|
||||
|
||||
public String getRedirectUri() {
|
||||
return redirectUri;
|
||||
}
|
||||
|
@ -73,19 +69,16 @@ public class CacheBean {
|
|||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "CacheBean [token=" + token + ", scope=" + scope
|
||||
+ ", redirectUri=" + redirectUri + ", clientId=" + clientId
|
||||
+ ", insertTime=" + insertTime + "]";
|
||||
}
|
||||
|
||||
/**
|
||||
* True if the code expired, false otherwise
|
||||
* @return
|
||||
*/
|
||||
public static boolean isExpired(CacheBean bean){
|
||||
|
||||
return System.currentTimeMillis() > TOKEN_TTL + bean.insertTime;
|
||||
|
||||
}
|
||||
|
||||
StringBuilder builder = new StringBuilder();
|
||||
builder.append("CacheBean [token=");
|
||||
builder.append(token);
|
||||
builder.append(", scope=");
|
||||
builder.append(scope);
|
||||
builder.append(", redirectUri=");
|
||||
builder.append(redirectUri);
|
||||
builder.append(", clientId=");
|
||||
builder.append(clientId);
|
||||
builder.append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,63 +0,0 @@
|
|||
package org.gcube.portal.oauth.cache;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
|
||||
/**
|
||||
* This thread cleans a cache by removing expired entries.
|
||||
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
|
||||
*/
|
||||
public class CacheCleaner extends Thread {
|
||||
|
||||
private Map<String, CacheBean> cacheReference;
|
||||
private static final int CHECK_AFTER_MS = 1000 * 60 * 10;
|
||||
|
||||
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(CacheCleaner.class);
|
||||
|
||||
/**
|
||||
* Build a cleaner thread.
|
||||
* @param cache
|
||||
*/
|
||||
public CacheCleaner(Map<String, CacheBean> cache) {
|
||||
this.cacheReference = cache;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
|
||||
while (!isInterrupted()) {
|
||||
|
||||
try {
|
||||
|
||||
sleep(CHECK_AFTER_MS);
|
||||
logger.info("Going to clean up cache and old codes [" + new Date() + "]");
|
||||
|
||||
int removedEntries = 0;
|
||||
|
||||
Iterator<Entry<String, CacheBean>> iterator = cacheReference.entrySet().iterator();
|
||||
while (iterator.hasNext()) {
|
||||
Map.Entry<java.lang.String, org.gcube.portal.oauth.cache.CacheBean> entry = (Map.Entry<java.lang.String, org.gcube.portal.oauth.cache.CacheBean>) iterator
|
||||
.next();
|
||||
if(CacheBean.isExpired(entry.getValue())){
|
||||
logger.debug("Removing entry " + entry.getValue());
|
||||
removedEntries ++;
|
||||
iterator.remove();
|
||||
}
|
||||
}
|
||||
|
||||
logger.info("Going to sleep. Number of removed entries is " + removedEntries + " [" + new Date() + "]");
|
||||
|
||||
} catch (InterruptedException e) {
|
||||
logger.warn("Exception was " + e.getMessage());
|
||||
continue;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue