changeset 21:0cd1e7608d25

works with new JWT-Auth now!
author casties
date Mon, 02 Apr 2012 19:30:46 +0200
parents 6629e8422760
children 0f4428febcc6
files .classpath src/de/mpiwg/itgroup/annotationManager/restlet/AnnotatorAnnotations.java src/de/mpiwg/itgroup/annotationManager/restlet/AnnotatorResourceImpl.java src/de/mpiwg/itgroup/annotationManager/restlet/RestServer.java
diffstat 4 files changed, 37 insertions(+), 95 deletions(-) [+]
line wrap: on
line diff
--- a/.classpath	Fri Mar 23 21:41:53 2012 +0100
+++ b/.classpath	Mon Apr 02 19:30:46 2012 +0200
@@ -23,7 +23,7 @@
 			<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
 		</attributes>
 	</classpathentry>
-	<classpathentry kind="lib" path="libs/jsontoken-1.1-SNAPSHOT.jar">
+	<classpathentry kind="lib" path="libs/jsontoken-1.1-SNAPSHOT.jar" sourcepath="/jsontoken/src/main/java">
 		<attributes>
 			<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
 		</attributes>
--- a/src/de/mpiwg/itgroup/annotationManager/restlet/AnnotatorAnnotations.java	Fri Mar 23 21:41:53 2012 +0100
+++ b/src/de/mpiwg/itgroup/annotationManager/restlet/AnnotatorAnnotations.java	Mon Apr 02 19:30:46 2012 +0200
@@ -292,7 +292,6 @@
     @Put("json")
     public Representation doPutJSON(Representation entity) {
         logger.debug("AnnotatorAnnotations doPutJSON!");
-        Reference thisUrl = this.getReference();
         setCorsHeaders();
         // id from URI /annotations/{id}
         String jsonId = (String) getRequest().getAttributes().get("id");
@@ -330,10 +329,16 @@
             // store Annotation
             storedAnnot = new Convert("file:///annotations").storeAnnotation(annot);
             /* according to https://github.com/okfn/annotator/wiki/Storage
-             * we should return 303: see other. */
+             * we should return 303: see other.
+             * but the client doesn't like it
             setStatus(Status.REDIRECTION_SEE_OTHER);
             // go to same URL as this one
-            this.getResponse().setLocationRef(thisUrl);
+            Reference thisUrl = this.getReference();
+            this.getResponse().setLocationRef(thisUrl); */
+            // return new annotation
+            jo = createAnnotatorJson(storedAnnot);
+            JsonRepresentation retRep = new JsonRepresentation(jo);
+            return retRep;
         } catch (TripleStoreHandlerException e) {
             e.printStackTrace();
             setStatus(Status.SERVER_ERROR_INTERNAL, "TripleStoreHandler Error");
--- a/src/de/mpiwg/itgroup/annotationManager/restlet/AnnotatorResourceImpl.java	Fri Mar 23 21:41:53 2012 +0100
+++ b/src/de/mpiwg/itgroup/annotationManager/restlet/AnnotatorResourceImpl.java	Mon Apr 02 19:30:46 2012 +0200
@@ -6,8 +6,10 @@
 import java.io.UnsupportedEncodingException;
 import java.net.URLDecoder;
 import java.net.URLEncoder;
+import java.security.InvalidKeyException;
 import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
+import java.security.SignatureException;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.regex.Matcher;
@@ -15,8 +17,15 @@
 
 import javax.xml.bind.DatatypeConverter;
 
+import net.oauth.jsontoken.Checker;
 import net.oauth.jsontoken.JsonToken;
 import net.oauth.jsontoken.JsonTokenParser;
+import net.oauth.jsontoken.SystemClock;
+import net.oauth.jsontoken.crypto.HmacSHA256Verifier;
+import net.oauth.jsontoken.crypto.SignatureAlgorithm;
+import net.oauth.jsontoken.crypto.Verifier;
+import net.oauth.jsontoken.discovery.VerifierProvider;
+import net.oauth.jsontoken.discovery.VerifierProviders;
 
 import org.apache.log4j.Logger;
 import org.json.JSONArray;
@@ -142,9 +151,9 @@
     public String checkAuthToken(Representation entity) {
         Form requestHeaders = (Form) getRequest().getAttributes().get("org.restlet.http.headers");
         String authToken = requestHeaders.getFirstValue("x-annotator-auth-token", true);
-        String userId = null;
-        String tokenString;
+        // decode token first to get consumer key
         JsonToken token = new JsonTokenParser(null, null).deserialize(authToken);
+        String userId = token.getParamAsPrimitive("userId").getAsString();
         String consumerKey = token.getParamAsPrimitive("consumerKey").getAsString();
         // get stored consumer secret for key
         RestServer restServer = (RestServer) getApplication();
@@ -153,92 +162,23 @@
         if (consumerSecret == null) {
             return null;
         }
-        logger.debug("token="+token);
-        /* try {
-            logger.debug(String.format("authToken=%s", authToken));
-            String[] tokenParts = authToken.split("\\.");
-            logger.debug(String.format("tokenParts=%s", tokenParts.toString()));
-            String payloadEnc = tokenParts[1];
-            if (payloadEnc.length() % 4 > 0) {
-                // add padding for parseBase64Binary
-                payloadEnc += "===".substring(0, payloadEnc.length() % 4);
-            }
-            String payloadString = new String(DatatypeConverter.parseBase64Binary(payloadEnc), "UTF-8");
-            logger.debug(String.format("payloadString=%s", payloadString));
-            JSONObject to = new JSONObject(payloadString);
-            logger.debug(String.format("jsonToken=%s", to));
-            String consumerKey = to.getString("consumerKey");
-            // get stored consumer secret for key
-            RestServer restServer = (RestServer) getApplication();
-            String consumerSecret = restServer.getConsumerSecret(consumerKey);
-            logger.debug("requested consumer key=" + consumerKey + " secret=" + consumerSecret);
-            if (consumerSecret == null) {
-                return null;
-            }
-            String decrypted = WebToken.decrypt(authToken, consumerSecret);
-            logger.debug("decrypted="+decrypted);
+        //logger.debug(String.format("token=%s tokenString=%s signatureAlgorithm=%s",token,token.getTokenString(),token.getSignatureAlgorithm()));
+        try {
+            List<Verifier> verifiers = new ArrayList<Verifier>();
+            // we only do HS256 yet
+            verifiers.add(new HmacSHA256Verifier(consumerSecret.getBytes("UTF-8")));
+            // verify token signature(should really be static...)
+            new JsonTokenParser(new SystemClock(), null, (Checker[]) null).verify(token, verifiers);
+        } catch (SignatureException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } catch (InvalidKeyException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
         } catch (UnsupportedEncodingException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
-        } catch (JSONException e) {
-            // TODO Auto-generated catch block
-            e.printStackTrace();
-        } catch (ArrayIndexOutOfBoundsException e) {
-            e.printStackTrace();
-        } catch (Exception e) {
-            // TODO Auto-generated catch block
-            e.printStackTrace();
-        } */
-        //WebToken.decrypt(encrypted, password)
-        /*
-        String consumerKey = requestHeaders.getFirstValue("x-annotator-consumer-key", true);
-        if (consumerKey == null) {
-            return null;
         }
-        // get stored consumer secret for key
-        RestServer restServer = (RestServer) getApplication();
-        String consumerSecret = restServer.getConsumerSecret(consumerKey);
-        logger.debug("requested consumer key=" + consumerKey + " secret=" + consumerSecret);
-        if (consumerSecret == null) {
-            return null;
-        }
-        String userId = requestHeaders.getFirstValue("x-annotator-user-id", true);
-        String issueTime = requestHeaders.getFirstValue("x-annotator-auth-token-issue-time", true);
-        if (userId == null || issueTime == null) {
-            return null;
-        }
-        // compute hashed token based on the values we know
-        // computed_token = hashlib.sha256(consumer.secret + user_id + issue_time).hexdigest()
-        String computedToken = getSha256Digest(consumerSecret + userId + issueTime);
-        // compare to the token we got
-        String authToken = requestHeaders.getFirstValue("x-annotator-auth-token", true);
-        logger.debug(String.format("got: authToken=%s consumerSecret=%s userId=%s issueTime=%s computedToken=%s", 
-                authToken, consumerSecret, userId, issueTime, computedToken));
-        if (!computedToken.equalsIgnoreCase(authToken)) {
-            logger.warn("authToken differ!");
-            return null;
-        }
-        // check token lifetime
-        // validity = iso8601.parse_date(issue_time)
-        // expiry = validity + datetime.timedelta(seconds=consumer.ttl)
-        int tokenTtl = 86400;
-        DateTime tokenValidity = null;
-        DateTime tokenExpiry = null;
-        try {
-            DateTimeFormatter parser = ISODateTimeFormat.dateTime();
-            tokenValidity = parser.parseDateTime(issueTime);
-            String tokenTtlString = requestHeaders.getFirstValue("x-annotator-auth-token-ttl", true);
-            tokenTtl = Integer.parseInt(tokenTtlString);
-            tokenExpiry = tokenValidity.plusSeconds(tokenTtl);
-        } catch (NumberFormatException e) {
-            e.printStackTrace();
-        }
-        if (tokenValidity == null || tokenValidity.isAfterNow() || tokenExpiry == null || tokenExpiry.isBeforeNow()) {
-            logger.warn(String.format("authToken invalid! tokenValidity=%s tokenExpiry=%s now=%s", tokenValidity, tokenExpiry, DateTime.now()));
-            // we dont care about validity right now
-            //return null;
-        }
-        */
         // must be ok then
         logger.debug("auth OK! user="+userId);
         return userId;
--- a/src/de/mpiwg/itgroup/annotationManager/restlet/RestServer.java	Fri Mar 23 21:41:53 2012 +0100
+++ b/src/de/mpiwg/itgroup/annotationManager/restlet/RestServer.java	Mon Apr 02 19:30:46 2012 +0200
@@ -42,6 +42,8 @@
 
 public class RestServer extends Application {
 
+    public static Logger logger = Logger.getRootLogger();
+    
     private ChallengeAuthenticator authenticator;
 
     /**
@@ -200,7 +202,7 @@
     }
 
     /**
-     * Authentifiziere den Benutzer aus dem Request (BasicAuthenfication)
+     * Authentifiziere den Benutzer aus dem Request (BasicAuthentication)
      * 
      * @param request
      * @param response
@@ -271,12 +273,7 @@
         String sp = "com.sun.jndi.ldap.LdapCtxFactory";
         env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, sp);
 
-        String ldapUrl = "ldap://ldapreplik.mpiwg-berlin.mpg.de/dc=mpiwg-berlin,dc=mpg,dc=de";// TODO
-                                                                                              // should
-                                                                                              // go
-                                                                                              // into
-                                                                                              // config
-                                                                                              // file
+        String ldapUrl = "ldap://ldapreplik.mpiwg-berlin.mpg.de/dc=mpiwg-berlin,dc=mpg,dc=de"; // TODO should go into config file
         env.put(javax.naming.Context.PROVIDER_URL, ldapUrl);
 
         DirContext dctx;