You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@shindig.apache.org by ss...@apache.org on 2012/05/10 02:48:42 UTC

svn commit: r1336461 [1/3] - in /shindig/trunk/java: common/conf/ gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/ gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/handler/ gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/persiste...

Author: ssievers
Date: Thu May 10 00:48:41 2012
New Revision: 1336461

URL: http://svn.apache.org/viewvc?rev=1336461&view=rev
Log:
SHINDIG-1732 | Restrictive OAuth2Client (endpoint whitelisting) | Patch from Adam Clarke.  Thanks!

Added:
    shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2CallbackState.java   (with props)
    shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2CallbackStateToken.java   (with props)
    shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/persistence/MapCache.java   (with props)
Modified:
    shindig/trunk/java/common/conf/shindig.properties
    shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/BasicOAuth2Accessor.java
    shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/BasicOAuth2Request.java
    shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/BasicOAuth2Store.java
    shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2Accessor.java
    shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2Error.java
    shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2FetcherConfig.java
    shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2Message.java
    shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2Module.java
    shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2Store.java
    shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2Token.java
    shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/handler/CodeAuthorizationResponseHandler.java
    shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/handler/CodeGrantTypeHandler.java
    shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/handler/OAuth2HandlerModule.java
    shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/handler/TokenAuthorizationResponseHandler.java
    shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/persistence/OAuth2Cache.java
    shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/persistence/OAuth2Client.java
    shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/persistence/OAuth2Persister.java
    shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/persistence/OAuth2TokenPersistence.java
    shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/persistence/sample/InMemoryCache.java
    shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/persistence/sample/JSONOAuth2Persister.java
    shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/servlet/MakeRequestHandler.java
    shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/servlet/OAuth2CallbackServlet.java
    shindig/trunk/java/gadgets/src/test/java/org/apache/shindig/gadgets/oauth2/MockUtils.java
    shindig/trunk/java/gadgets/src/test/java/org/apache/shindig/gadgets/oauth2/handler/CodeGrantTypeHandlerTest.java
    shindig/trunk/java/gadgets/src/test/java/org/apache/shindig/gadgets/oauth2/handler/TokenAuthorizationResponseHandlerTest.java
    shindig/trunk/java/gadgets/src/test/java/org/apache/shindig/gadgets/oauth2/persistence/OAuth2ClientTest.java
    shindig/trunk/java/gadgets/src/test/java/org/apache/shindig/gadgets/oauth2/persistence/sample/InMemoryCacheTest.java
    shindig/trunk/java/gadgets/src/test/java/org/apache/shindig/gadgets/oauth2/persistence/sample/JSONOAuth2PersisterTest.java
    shindig/trunk/java/gadgets/src/test/java/org/apache/shindig/gadgets/servlet/MakeRequestHandlerTest.java
    shindig/trunk/java/gadgets/src/test/resources/org/apache/shindig/gadgets/oauth2/oauth2_test.json

Modified: shindig/trunk/java/common/conf/shindig.properties
URL: http://svn.apache.org/viewvc/shindig/trunk/java/common/conf/shindig.properties?rev=1336461&r1=1336460&r2=1336461&view=diff
==============================================================================
--- shindig/trunk/java/common/conf/shindig.properties (original)
+++ shindig/trunk/java/common/conf/shindig.properties Thu May 10 00:48:41 2012
@@ -49,6 +49,7 @@ shindig.oauth2.viewer-access-tokens-enab
 # Set to true to send extended trace messages to the client.  Probably want this to be false for
 # production systems and true for test/development.
 shindig.oauth2.send-trace-to-client=true
+shindig.signing.oauth2.state-key=
 
 # Set to true if you want to allow the use of 3-legged OAuth tokens when viewer != owner.
 # This setting is not recommeneded for pages that allow user-controlled javascript, since

Modified: shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/BasicOAuth2Accessor.java
URL: http://svn.apache.org/viewvc/shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/BasicOAuth2Accessor.java?rev=1336461&r1=1336460&r2=1336461&view=diff
==============================================================================
--- shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/BasicOAuth2Accessor.java (original)
+++ shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/BasicOAuth2Accessor.java Thu May 10 00:48:41 2012
@@ -1,23 +1,27 @@
 /*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with this
- * work for additional information regarding copyright ownership. The ASF
- * licenses this file to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
  *
- * http://www.apache.org/licenses/LICENSE-2.0
+ *   http://www.apache.org/licenses/LICENSE-2.0
  *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package org.apache.shindig.gadgets.oauth2;
 
 import com.google.common.collect.Maps;
 
+import org.apache.shindig.common.servlet.Authority;
+
 import java.util.Map;
 
 /**
@@ -25,8 +29,7 @@ import java.util.Map;
  * see {@link OAuth2Accessor}
  */
 public class BasicOAuth2Accessor implements OAuth2Accessor {
-  private static final long serialVersionUID = 3347883060790082094L;
-
+  private static final long serialVersionUID = 2050065428260384933L;
   private OAuth2Token accessToken;
   private final boolean allowModuleOverrides;
   private boolean authorizationHeader;
@@ -41,18 +44,25 @@ public class BasicOAuth2Accessor impleme
   private String errorUri;
   private final String gadgetUri;
   private final String globalRedirectUri;
+  private final transient Authority authority;
+  private final transient String contextRoot;
   private String grantType;
   private boolean redirecting;
   private String redirectUri;
   private OAuth2Token refreshToken;
   private final String scope;
   private final String serviceName;
-  private final String state;
+  private transient OAuth2CallbackState state;
   private String tokenUrl;
   private Type type;
   private boolean urlParameter;
   private final String user;
   private Map<String, String> additionalRequestParams;
+  private String[] allowedDomains;
+
+  public BasicOAuth2Accessor() {
+    this(null, null, null, null, false, null, null, null, null);
+  }
 
   BasicOAuth2Accessor(final Throwable exception, final OAuth2Error error,
           final String contextMessage, final String errorUri) {
@@ -64,6 +74,8 @@ public class BasicOAuth2Accessor impleme
     this.user = null;
     this.gadgetUri = null;
     this.globalRedirectUri = null;
+    this.authority = null;
+    this.contextRoot = null;
     this.allowModuleOverrides = false;
     this.additionalRequestParams = Maps.newHashMap();
     this.setErrorResponse(exception, error, contextMessage, errorUri);
@@ -89,6 +101,8 @@ public class BasicOAuth2Accessor impleme
     this.user = accessor.getUser();
     this.allowModuleOverrides = false;
     this.globalRedirectUri = null;
+    this.authority = null;
+    this.contextRoot = null;
     this.errorResponse = accessor.isErrorResponse();
     this.redirecting = accessor.isRedirecting();
     this.error = accessor.getError();
@@ -96,18 +110,29 @@ public class BasicOAuth2Accessor impleme
     this.errorException = accessor.getErrorException();
     this.errorUri = accessor.getErrorUri();
     this.additionalRequestParams = Maps.newHashMap();
+    this.allowedDomains = accessor.getAllowedDomains();
   }
 
   public BasicOAuth2Accessor(final String gadgetUri, final String serviceName, final String user,
           final String scope, final boolean allowModuleOverrides, final OAuth2Store store,
-          final String globalRedirectUri) {
+          final String globalRedirectUri, final Authority authority, final String contextRoot) {
     this.gadgetUri = gadgetUri;
     this.serviceName = serviceName;
     this.user = user;
     this.scope = scope;
     this.allowModuleOverrides = allowModuleOverrides;
     this.globalRedirectUri = globalRedirectUri;
-    this.state = store.getOAuth2AccessorIndex(gadgetUri, serviceName, user, scope).toString();
+    if (store != null) {
+      this.state = new OAuth2CallbackState(store.getStateCrypter());
+    } else {
+      this.state = new OAuth2CallbackState();
+    }
+    this.state.setGadgetUri(gadgetUri);
+    this.state.setServiceName(serviceName);
+    this.state.setUser(user);
+    this.state.setScope(scope);
+    this.authority = authority;
+    this.contextRoot = contextRoot;
     this.errorResponse = false;
     this.redirecting = false;
     this.additionalRequestParams = Maps.newHashMap();
@@ -158,9 +183,17 @@ public class BasicOAuth2Accessor impleme
   }
 
   public String getRedirectUri() {
-    if ((this.redirectUri == null) || (this.redirectUri.length() == 0)) {
-      return this.globalRedirectUri;
+    if (this.redirectUri == null || this.redirectUri.length() == 0) {
+      String redirectUri2 = this.globalRedirectUri;
+      if (this.authority != null) {
+        redirectUri2 = redirectUri2.replace("%authority%", this.authority.getAuthority());
+        redirectUri2 = redirectUri2.replace("%contextRoot%", this.contextRoot);
+        redirectUri2 = redirectUri2.replace("%origin%", this.authority.getOrigin());
+      }
+
+      this.redirectUri = redirectUri2;
     }
+
     return this.redirectUri;
   }
 
@@ -180,7 +213,10 @@ public class BasicOAuth2Accessor impleme
     return this.serviceName;
   }
 
-  public String getState() {
+  public OAuth2CallbackState getState() {
+    if (this.state == null) {
+      return new OAuth2CallbackState(null);
+    }
     return this.state;
   }
 
@@ -233,14 +269,14 @@ public class BasicOAuth2Accessor impleme
   }
 
   public boolean isValid() {
-    return (this.grantType != null);
+    return this.grantType != null;
   }
 
   public void setAccessToken(final OAuth2Token accessToken) {
     this.accessToken = accessToken;
   }
 
-  public void setAuthorizationHeader(boolean authorizationHeader) {
+  public void setAuthorizationHeader(final boolean authorizationHeader) {
     this.authorizationHeader = authorizationHeader;
   }
 
@@ -260,8 +296,8 @@ public class BasicOAuth2Accessor impleme
     this.clientSecret = clientSecret;
   }
 
-  public void setErrorResponse(Throwable exception, OAuth2Error error, String contextMessage,
-          String errorUri) {
+  public void setErrorResponse(final Throwable exception, final OAuth2Error error,
+          final String contextMessage, final String errorUri) {
     this.errorResponse = true;
     this.errorException = exception;
     if (error != null) {
@@ -271,7 +307,7 @@ public class BasicOAuth2Accessor impleme
     }
   }
 
-  public void setErrorUri(String errorUri) {
+  public void setErrorUri(final String errorUri) {
     this.errorUri = errorUri;
   }
 
@@ -279,7 +315,7 @@ public class BasicOAuth2Accessor impleme
     this.grantType = grantType;
   }
 
-  public void setRedirecting(boolean redirecting) {
+  public void setRedirecting(final boolean redirecting) {
     this.redirecting = redirecting;
   }
 
@@ -291,7 +327,7 @@ public class BasicOAuth2Accessor impleme
     this.refreshToken = refreshToken;
   }
 
-  public void setAdditionalRequestParams(Map<String, String> additionalRequestParams) {
+  public void setAdditionalRequestParams(final Map<String, String> additionalRequestParams) {
     this.additionalRequestParams = additionalRequestParams;
   }
 
@@ -303,7 +339,15 @@ public class BasicOAuth2Accessor impleme
     this.type = type;
   }
 
-  public void setUrlParameter(boolean urlParameter) {
+  public void setUrlParameter(final boolean urlParameter) {
     this.urlParameter = urlParameter;
   }
+
+  public void setAllowedDomains(final String[] allowedDomains) {
+    this.allowedDomains = allowedDomains;
+  }
+
+  public String[] getAllowedDomains() {
+    return this.allowedDomains;
+  }
 }

Modified: shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/BasicOAuth2Request.java
URL: http://svn.apache.org/viewvc/shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/BasicOAuth2Request.java?rev=1336461&r1=1336460&r2=1336461&view=diff
==============================================================================
--- shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/BasicOAuth2Request.java (original)
+++ shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/BasicOAuth2Request.java Thu May 10 00:48:41 2012
@@ -1,26 +1,25 @@
 /*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with this
- * work for additional information regarding copyright ownership. The ASF
- * licenses this file to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
  *
- * http://www.apache.org/licenses/LICENSE-2.0
+ *   http://www.apache.org/licenses/LICENSE-2.0
  *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package org.apache.shindig.gadgets.oauth2;
 
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.io.UnsupportedEncodingException;
-import java.util.List;
-import java.util.Map;
+import com.google.common.collect.Maps;
+import com.google.inject.Inject;
 
 import org.apache.shindig.auth.SecurityToken;
 import org.apache.shindig.common.uri.Uri;
@@ -37,19 +36,23 @@ import org.apache.shindig.gadgets.oauth2
 import org.apache.shindig.gadgets.oauth2.handler.TokenEndpointResponseHandler;
 import org.apache.shindig.gadgets.oauth2.logger.FilteredLogger;
 
-import com.google.common.collect.Maps;
-import com.google.inject.Inject;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.io.UnsupportedEncodingException;
+import java.util.List;
+import java.util.Map;
+import java.util.logging.Level;
 
 /**
  * see {@link OAuth2Request}
  *
  */
 public class BasicOAuth2Request implements OAuth2Request {
-  private final static String LOG_CLASS = BasicOAuth2Request.class.getName();
-  private final static FilteredLogger LOG = FilteredLogger
+  private static final String LOG_CLASS = BasicOAuth2Request.class.getName();
+  private static final FilteredLogger LOG = FilteredLogger
           .getFilteredLogger(BasicOAuth2Request.LOG_CLASS);
 
-  private OAuth2Accessor _accessor;
+  private OAuth2Accessor internalAccessor;
 
   private OAuth2Arguments arguments;
 
@@ -138,7 +141,7 @@ public class BasicOAuth2Request implemen
 
     try {
       // First step is to get an OAuth2Accessor for this request
-      if ((request == null) || (request.getSecurityToken() == null)) {
+      if (request == null || request.getSecurityToken() == null) {
         // Any errors before we have an accessor are special cases
         response = this.sendErrorResponse(null, OAuth2Error.MISSING_FETCH_PARAMS,
                 "no request or security token", "");
@@ -155,7 +158,7 @@ public class BasicOAuth2Request implemen
           BasicOAuth2Request.LOG.log("this.arguments = {0}", this.arguments);
         }
 
-        if ((this.responseParams == null) || (this.arguments == null)) {
+        if (this.responseParams == null || this.arguments == null) {
           // Any errors before we have an accessor are special cases
           return this.sendErrorResponse(null, OAuth2Error.FETCH_INIT_PROBLEM,
                   "no responseParams or arguments", "");
@@ -174,13 +177,13 @@ public class BasicOAuth2Request implemen
         } else {
           accessor.setRedirecting(false);
 
-          Map<String, String> requestParams = requestParameterGenerator
+          final Map<String, String> requestParams = this.requestParameterGenerator
                   .generateParams(this.realRequest);
           accessor.setAdditionalRequestParams(requestParams);
 
           HttpResponseBuilder responseBuilder = null;
           if (!accessor.isErrorResponse()) {
-            responseBuilder = this.attemptFetch(accessor, false);
+            responseBuilder = this.attemptFetch(accessor);
           }
 
           response = this.processResponse(accessor, responseBuilder);
@@ -204,7 +207,9 @@ public class BasicOAuth2Request implemen
         if (!accessor.isRedirecting()) {
           accessor.invalidate();
           this.store.removeOAuth2Accessor(accessor);
-          this._accessor = null;
+          this.internalAccessor = null;
+        } else {
+          this.store.storeOAuth2Accessor(accessor);
         }
       }
     }
@@ -216,17 +221,19 @@ public class BasicOAuth2Request implemen
     return response;
   }
 
-  private HttpResponseBuilder attemptFetch(final OAuth2Accessor accessor, final boolean tryAgain) {
+  private HttpResponseBuilder attemptFetch(final OAuth2Accessor accessor) {
     final boolean isLogging = BasicOAuth2Request.LOG.isLoggable();
     if (isLogging) {
-      BasicOAuth2Request.LOG.entering(BasicOAuth2Request.LOG_CLASS, "attemptFetch", new Object[] {
-              accessor, tryAgain });
+      BasicOAuth2Request.LOG.entering(BasicOAuth2Request.LOG_CLASS, "attemptFetch",
+              new Object[] { accessor });
     }
 
     HttpResponseBuilder ret = null;
 
-    // If there's an error in the accessor don't continue.
-    if (!accessor.isErrorResponse()) {
+    if (accessor.isErrorResponse()) {
+      // If there's an error in the accessor don't continue.
+      return null;
+    } else {
       if (BasicOAuth2Request.haveAccessToken(accessor) != null) {
         // We have an access_token, use it and stop!
         ret = this.fetchData(accessor);
@@ -238,7 +245,10 @@ public class BasicOAuth2Request implemen
             final OAuth2HandlerError handlerError = this.refreshToken(accessor);
             if (handlerError == null) {
               // No errors refreshing, attempt the fetch again.
-              ret = this.attemptFetch(accessor, true);
+              this.store.removeOAuth2Accessor(accessor);
+              this.internalAccessor.invalidate();
+              this.internalAccessor = null;
+              ret = this.attemptFetch(this.getAccessor());
             } else {
               // There was an error refreshing, stop.
               final OAuth2Error error = handlerError.getError();
@@ -248,7 +258,7 @@ public class BasicOAuth2Request implemen
           } else {
             // User cannot refresh, they'll have to try to authorize again.
             accessor.setRefreshToken(null);
-            ret = this.attemptFetch(accessor, true);
+            ret = this.attemptFetch(accessor);
           }
         } else {
           // We have no access token and no refresh token.
@@ -261,23 +271,21 @@ public class BasicOAuth2Request implemen
               accessor.setRedirecting(true);
             } else {
               // This wasn't a redirect type of authorization. try again
-              ret = this.attemptFetch(accessor, true);
+              ret = this.attemptFetch(accessor);
             }
           }
         }
       }
 
-      if ((ret == null) && (!accessor.isRedirecting())) {
-        // We don't have a response, just issue the request and
-        // see what happens
-        ret = this.fetchData(accessor);
-      }
-
-      if ((ret == null) && (accessor.isRedirecting())) {
-        ret = new HttpResponseBuilder().setHttpStatusCode(HttpResponse.SC_OK).setStrictNoCache();
+      if (ret == null) {
+        if (accessor.isRedirecting()) {
+          // Send redirect response to client
+          ret = new HttpResponseBuilder().setHttpStatusCode(HttpResponse.SC_OK).setStrictNoCache();
+        } else {
+          accessor.setAccessToken(null);
+          ret = this.attemptFetch(accessor);
+        }
       }
-    } else {
-      return null;
     }
 
     if (isLogging) {
@@ -463,7 +471,7 @@ public class BasicOAuth2Request implemen
       BasicOAuth2Request.LOG.log("pageViewer = {0}", pageViewer);
     }
 
-    if ((pageOwner == null) || (pageViewer == null)) {
+    if (pageOwner == null || pageViewer == null) {
       accessor.setErrorResponse(null, OAuth2Error.AUTHORIZE_PROBLEM,
               "pageOwner or pageViewer is null", "");
       ret = false;
@@ -491,14 +499,16 @@ public class BasicOAuth2Request implemen
       BasicOAuth2Request.LOG.entering(BasicOAuth2Request.LOG_CLASS, "fetchData", accessor);
     }
 
-    HttpResponseBuilder ret;
+    HttpResponseBuilder ret = null;
 
     try {
       final HttpResponse response = this.fetchFromServer(accessor, this.realRequest);
-      ret = new HttpResponseBuilder(response);
+      if (response != null) {
+        ret = new HttpResponseBuilder(response);
 
-      if ((response.getHttpStatusCode() != HttpResponse.SC_OK) && (this.sendTraceToClient)) {
-        this.responseParams.addRequestTrace(this.realRequest, response);
+        if (response.getHttpStatusCode() != HttpResponse.SC_OK && this.sendTraceToClient) {
+          this.responseParams.addRequestTrace(this.realRequest, response);
+        }
       }
     } catch (final OAuth2RequestException e) {
       ret = this.getErrorResponseBuilder(e, e.getError(), e.getErrorText(), "");
@@ -521,8 +531,49 @@ public class BasicOAuth2Request implemen
 
     HttpResponse ret;
 
-    final OAuth2Token accessToken = accessor.getAccessToken();
-    final OAuth2Token refreshToken = accessor.getRefreshToken();
+    final long currentTime = System.currentTimeMillis();
+
+    OAuth2Token accessToken = accessor.getAccessToken();
+    if (accessToken != null) {
+      final long expiresAt = accessToken.getExpiresAt();
+      if (expiresAt != 0) {
+        if (currentTime >= expiresAt) {
+          accessToken = null;
+          if (BasicOAuth2Request.LOG.isLoggable()) {
+            BasicOAuth2Request.LOG.log("accessToken has expired at {0}", expiresAt);
+          }
+          try {
+            this.store.removeToken(accessToken);
+          } catch (final GadgetException e) {
+            throw new OAuth2RequestException(OAuth2Error.MISSING_SERVER_RESPONSE,
+                    "error removing access_token", null);
+          }
+          accessor.setAccessToken(null);
+          return null;
+        }
+      }
+    }
+
+    OAuth2Token refreshToken = accessor.getRefreshToken();
+    if (refreshToken != null) {
+      final long expiresAt = refreshToken.getExpiresAt();
+      if (expiresAt != 0) {
+        if (currentTime >= expiresAt) {
+          refreshToken = null;
+          if (BasicOAuth2Request.LOG.isLoggable()) {
+            BasicOAuth2Request.LOG.log("refreshToken has expired at {0}", expiresAt);
+          }
+          try {
+            this.store.removeToken(refreshToken);
+          } catch (final GadgetException e) {
+            throw new OAuth2RequestException(OAuth2Error.MISSING_SERVER_RESPONSE,
+                    "error removing refresh_token", null);
+          }
+          accessor.setRefreshToken(null);
+          return null;
+        }
+      }
+    }
 
     if (BasicOAuth2Request.LOG.isLoggable()) {
       BasicOAuth2Request.LOG.log("accessToken = {0}", accessToken);
@@ -530,15 +581,22 @@ public class BasicOAuth2Request implemen
     }
 
     if (accessToken != null) {
-      String tokenType = accessToken.getTokenType();
-      if ((tokenType == null) || (tokenType.length() == 0)) {
-        tokenType = OAuth2Message.BEARER_TOKEN_TYPE;
-      }
+      final boolean isAllowed = isUriAllowed(request.getUri(), accessor.getAllowedDomains());
+      if (isAllowed) {
+        String tokenType = accessToken.getTokenType();
+        if (tokenType == null || tokenType.length() == 0) {
+          tokenType = OAuth2Message.BEARER_TOKEN_TYPE;
+        }
 
-      for (final ResourceRequestHandler resourceRequestHandler : this.resourceRequestHandlers) {
-        if (tokenType.equalsIgnoreCase(resourceRequestHandler.getTokenType())) {
-          resourceRequestHandler.addOAuth2Params(accessor, request);
+        for (final ResourceRequestHandler resourceRequestHandler : this.resourceRequestHandlers) {
+          if (tokenType.equalsIgnoreCase(resourceRequestHandler.getTokenType())) {
+            resourceRequestHandler.addOAuth2Params(accessor, request);
+          }
         }
+      } else {
+        BasicOAuth2Request.LOG.log(Level.WARNING,
+                "Gadget {0} attempted to send OAuth2 Token to an unauthorized domain: {1}.",
+                new Object[] { accessor.getGadgetUri(), request.getUri() });
       }
     }
 
@@ -571,15 +629,7 @@ public class BasicOAuth2Request implemen
         accessor.setAccessToken(null);
       }
 
-      if (refreshToken != null) {
-        try {
-          this.store.removeToken(refreshToken);
-        } catch (final GadgetException e) {
-          throw new OAuth2RequestException(OAuth2Error.MISSING_SERVER_RESPONSE,
-                  "error removing refresh_token", null);
-        }
-        accessor.setRefreshToken(null);
-      }
+      ret = null;
     }
 
     if (isLogging) {
@@ -590,17 +640,17 @@ public class BasicOAuth2Request implemen
   }
 
   private OAuth2Accessor getAccessor() {
-    if ((this._accessor == null) || (!this._accessor.isValid())) {
+    if (this.internalAccessor == null || !this.internalAccessor.isValid()) {
       if (this.fetcherConfig != null) {
         final GadgetOAuth2TokenStore tokenStore = this.fetcherConfig.getTokenStore();
         if (tokenStore != null) {
-          this._accessor = tokenStore.getOAuth2Accessor(this.securityToken, this.arguments,
+          this.internalAccessor = tokenStore.getOAuth2Accessor(this.securityToken, this.arguments,
                   this.realRequest.getGadget());
         }
       }
     }
 
-    return this._accessor;
+    return this.internalAccessor;
   }
 
   private static String getCompleteRefreshUrl(final String refreshUrl) {
@@ -619,7 +669,7 @@ public class BasicOAuth2Request implemen
     final HttpResponseBuilder ret = new HttpResponseBuilder().setHttpStatusCode(
             HttpResponse.SC_FORBIDDEN).setStrictNoCache();
 
-    if ((t != null) && (this.sendTraceToClient)) {
+    if (t != null && this.sendTraceToClient) {
       final StringWriter sw = new StringWriter();
       t.printStackTrace(new PrintWriter(sw));
       final String message = sw.toString();
@@ -650,7 +700,7 @@ public class BasicOAuth2Request implemen
       queryParams.put(OAuth2Message.GRANT_TYPE, OAuth2Message.REFRESH_TOKEN);
       queryParams.put(OAuth2Message.REFRESH_TOKEN, new String(accessor.getRefreshToken()
               .getSecret(), "UTF-8"));
-      if ((accessor.getScope() != null) && (accessor.getScope().length() > 0)) {
+      if (accessor.getScope() != null && accessor.getScope().length() > 0) {
         queryParams.put(OAuth2Message.SCOPE, accessor.getScope());
       }
 
@@ -662,7 +712,7 @@ public class BasicOAuth2Request implemen
       ret = OAuth2Utils.buildUrl(ret, queryParams, null);
 
       final char firstChar = ret.charAt(0);
-      if ((firstChar == '?') || (firstChar == '&')) {
+      if (firstChar == '?' || firstChar == '&') {
         ret = ret.substring(1);
       }
 
@@ -685,10 +735,10 @@ public class BasicOAuth2Request implemen
     final boolean isLogging = BasicOAuth2Request.LOG.isLoggable();
     if (isLogging) {
       BasicOAuth2Request.LOG.entering(BasicOAuth2Request.LOG_CLASS, "processResponse",
-              new Object[] { accessor, (responseBuilder == null) });
+              new Object[] { accessor, responseBuilder == null });
     }
 
-    if (accessor.isErrorResponse() || (responseBuilder == null)) {
+    if (accessor.isErrorResponse() || responseBuilder == null) {
       return this.sendErrorResponse(accessor.getErrorException(), accessor.getError(),
               accessor.getErrorContextMessage(), accessor.getErrorUri());
     }
@@ -751,6 +801,11 @@ public class BasicOAuth2Request implemen
                 "error generating refresh body", e);
       }
 
+      if (!isUriAllowed(request.getUri(), accessor.getAllowedDomains())) {
+        ret = new OAuth2HandlerError(OAuth2Error.REFRESH_TOKEN_PROBLEM,
+                "error fetching refresh token - domain not allowed", null);
+      }
+
       if (ret == null) {
         try {
           response = this.fetcher.fetch(request);
@@ -773,7 +828,15 @@ public class BasicOAuth2Request implemen
         if (ret == null) {
           // response is not null..
           final int statusCode = response.getHttpStatusCode();
-          if (statusCode != HttpResponse.SC_OK) {
+          if (statusCode == HttpResponse.SC_UNAUTHORIZED) {
+            try {
+              this.store.removeToken(accessor.getRefreshToken());
+            } catch (final GadgetException e) {
+              ret = new OAuth2HandlerError(OAuth2Error.REFRESH_TOKEN_PROBLEM,
+                      "failed to remove refresh token", e);
+            }
+            accessor.setRefreshToken(null);
+          } else if (statusCode != HttpResponse.SC_OK) {
             ret = new OAuth2HandlerError(OAuth2Error.REFRESH_TOKEN_PROBLEM,
                     "bad response from server : " + statusCode, null);
           }
@@ -815,7 +878,7 @@ public class BasicOAuth2Request implemen
     }
 
     OAuth2Token ret = accessor.getAccessToken();
-    if ((ret != null)) {
+    if (ret != null) {
       if (!BasicOAuth2Request.validateAccessToken(ret)) {
         ret = null;
       }
@@ -836,7 +899,7 @@ public class BasicOAuth2Request implemen
     }
 
     OAuth2Token ret = accessor.getRefreshToken();
-    if ((ret != null)) {
+    if (ret != null) {
       if (!BasicOAuth2Request.validateRefreshToken(ret)) {
         ret = null;
       }
@@ -849,6 +912,27 @@ public class BasicOAuth2Request implemen
     return ret;
   }
 
+  private static boolean isUriAllowed(final Uri uri, final String[] allowedDomains) {
+    if (allowedDomains == null || allowedDomains.length == 0) {
+      // if white list is not specified, allow client to access any domain
+      return true;
+    }
+    String host = uri.getAuthority();
+    final int pos = host.indexOf(':');
+    if (pos != -1) {
+      host = host.substring(0, pos);
+    }
+    for (String domain : allowedDomains) {
+      if (domain != null) {
+        domain = domain.trim();
+        if (domain.startsWith(".") && host.endsWith(domain) || domain.equals(host)) {
+          return true;
+        }
+      }
+    }
+    return false;
+  }
+
   private static boolean validateAccessToken(final OAuth2Token accessToken) {
     return accessToken != null;
   }

Modified: shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/BasicOAuth2Store.java
URL: http://svn.apache.org/viewvc/shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/BasicOAuth2Store.java?rev=1336461&r1=1336460&r2=1336461&view=diff
==============================================================================
--- shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/BasicOAuth2Store.java (original)
+++ shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/BasicOAuth2Store.java Thu May 10 00:48:41 2012
@@ -19,15 +19,20 @@
 package org.apache.shindig.gadgets.oauth2;
 
 import com.google.inject.Inject;
+import com.google.inject.name.Named;
 
+import org.apache.shindig.common.crypto.BlobCrypter;
+import org.apache.shindig.common.servlet.Authority;
 import org.apache.shindig.gadgets.GadgetException;
 import org.apache.shindig.gadgets.GadgetException.Code;
 import org.apache.shindig.gadgets.oauth2.logger.FilteredLogger;
 import org.apache.shindig.gadgets.oauth2.persistence.OAuth2Cache;
 import org.apache.shindig.gadgets.oauth2.persistence.OAuth2CacheException;
 import org.apache.shindig.gadgets.oauth2.persistence.OAuth2Client;
+import org.apache.shindig.gadgets.oauth2.persistence.OAuth2Encrypter;
 import org.apache.shindig.gadgets.oauth2.persistence.OAuth2PersistenceException;
 import org.apache.shindig.gadgets.oauth2.persistence.OAuth2Persister;
+import org.apache.shindig.gadgets.oauth2.persistence.OAuth2TokenPersistence;
 
 import java.util.Set;
 
@@ -42,24 +47,37 @@ import java.util.Set;
  *
  */
 public class BasicOAuth2Store implements OAuth2Store {
-  private final static String LOG_CLASS = BasicOAuth2Store.class.getName();
+  private static final String LOG_CLASS = BasicOAuth2Store.class.getName();
   private static final FilteredLogger LOG = FilteredLogger
           .getFilteredLogger(BasicOAuth2Store.LOG_CLASS);
 
   private final OAuth2Cache cache;
   private final String globalRedirectUri;
+  private final Authority authority;
+  private final String contextRoot;
   private final OAuth2Persister persister;
+  private final OAuth2Encrypter encrypter;
+  private final BlobCrypter stateCrypter;
 
   @Inject
   public BasicOAuth2Store(final OAuth2Cache cache, final OAuth2Persister persister,
-          final String globalRedirectUri) {
+          final OAuth2Encrypter encrypter, final String globalRedirectUri,
+          final Authority authority, final String contextRoot,
+          @Named(OAuth2FetcherConfig.OAUTH2_STATE_CRYPTER)
+          final BlobCrypter stateCrypter) {
     this.cache = cache;
     this.persister = persister;
     this.globalRedirectUri = globalRedirectUri;
+    this.authority = authority;
+    this.contextRoot = contextRoot;
+    this.encrypter = encrypter;
+    this.stateCrypter = stateCrypter;
     if (BasicOAuth2Store.LOG.isLoggable()) {
       BasicOAuth2Store.LOG.log("this.cache = {0}", this.cache);
       BasicOAuth2Store.LOG.log("this.persister = {0}", this.persister);
       BasicOAuth2Store.LOG.log("this.globalRedirectUri = {0}", this.globalRedirectUri);
+      BasicOAuth2Store.LOG.log("this.encrypter = {0}", this.encrypter);
+      BasicOAuth2Store.LOG.log("this.stateCrypter = {0}", this.stateCrypter);
     }
   }
 
@@ -72,6 +90,7 @@ public class BasicOAuth2Store implements
     try {
       this.cache.clearClients();
       this.cache.clearTokens();
+      this.cache.clearAccessors();
     } catch (final OAuth2PersistenceException e) {
       if (isLogging) {
         BasicOAuth2Store.LOG.log("Error clearing OAuth2 cache", e);
@@ -92,7 +111,7 @@ public class BasicOAuth2Store implements
       BasicOAuth2Store.LOG.entering(BasicOAuth2Store.LOG_CLASS, "createToken");
     }
 
-    final OAuth2Token ret = this.persister.createToken();
+    final OAuth2Token ret = this.internalCreateToken();
 
     if (isLogging) {
       BasicOAuth2Store.LOG.exiting(BasicOAuth2Store.LOG_CLASS, "clearCache", ret);
@@ -109,13 +128,7 @@ public class BasicOAuth2Store implements
               gadgetUri, serviceName });
     }
 
-    final Integer index = this.cache.getClientIndex(gadgetUri, serviceName);
-
-    if (isLogging) {
-      BasicOAuth2Store.LOG.log("index = {0}", index);
-    }
-
-    OAuth2Client client = this.cache.getClient(index);
+    OAuth2Client client = this.cache.getClient(gadgetUri, serviceName);
 
     if (isLogging) {
       BasicOAuth2Store.LOG.log("client from cache = {0}", client);
@@ -143,13 +156,13 @@ public class BasicOAuth2Store implements
     return client;
   }
 
-  public OAuth2Accessor getOAuth2Accessor(final Integer index) {
+  public OAuth2Accessor getOAuth2Accessor(final OAuth2CallbackState state) {
     final boolean isLogging = BasicOAuth2Store.LOG.isLoggable();
     if (isLogging) {
-      BasicOAuth2Store.LOG.entering(BasicOAuth2Store.LOG_CLASS, "getOAuth2Accessor", index);
+      BasicOAuth2Store.LOG.entering(BasicOAuth2Store.LOG_CLASS, "getOAuth2Accessor", state);
     }
 
-    final OAuth2Accessor ret = this.cache.getOAuth2Accessor(index);
+    final OAuth2Accessor ret = this.cache.getOAuth2Accessor(state);
 
     if (isLogging) {
       BasicOAuth2Store.LOG.exiting(BasicOAuth2Store.LOG_CLASS, "getOAuth2Accessor", ret);
@@ -166,11 +179,15 @@ public class BasicOAuth2Store implements
               gadgetUri, serviceName, user, scope });
     }
 
-    final Integer index = this.cache.getOAuth2AccessorIndex(gadgetUri, serviceName, user, scope);
+    final OAuth2CallbackState state = new OAuth2CallbackState(this.stateCrypter);
+    state.setGadgetUri(gadgetUri);
+    state.setServiceName(serviceName);
+    state.setUser(user);
+    state.setScope(scope);
 
-    OAuth2Accessor ret = this.cache.getOAuth2Accessor(index);
+    OAuth2Accessor ret = this.cache.getOAuth2Accessor(state);
 
-    if ((ret == null) || (!ret.isValid())) {
+    if (ret == null || !ret.isValid()) {
       final OAuth2Client client = this.getClient(gadgetUri, serviceName);
 
       if (client != null) {
@@ -180,7 +197,8 @@ public class BasicOAuth2Store implements
                 OAuth2Token.Type.REFRESH);
 
         final BasicOAuth2Accessor newAccessor = new BasicOAuth2Accessor(gadgetUri, serviceName,
-                user, scope, client.isAllowModuleOverride(), this, this.globalRedirectUri);
+                user, scope, client.isAllowModuleOverride(), this, this.globalRedirectUri,
+                this.authority, this.contextRoot);
         newAccessor.setAccessToken(accessToken);
         newAccessor.setAuthorizationUrl(client.getAuthorizationUrl());
         newAccessor.setClientAuthenticationType(client.getClientAuthenticationType());
@@ -193,6 +211,7 @@ public class BasicOAuth2Store implements
         newAccessor.setRefreshToken(refreshToken);
         newAccessor.setTokenUrl(client.getTokenUrl());
         newAccessor.setType(client.getType());
+        newAccessor.setAllowedDomains(client.getAllowedDomains());
         ret = newAccessor;
 
         this.storeOAuth2Accessor(ret);
@@ -206,11 +225,6 @@ public class BasicOAuth2Store implements
     return ret;
   }
 
-  public Integer getOAuth2AccessorIndex(final String gadgetUri, final String serviceName,
-          final String user, final String scope) {
-    return this.cache.getOAuth2AccessorIndex(gadgetUri, serviceName, user, scope);
-  }
-
   public OAuth2Token getToken(final String gadgetUri, final String serviceName, final String user,
           final String scope, final OAuth2Token.Type type) throws GadgetException {
 
@@ -222,9 +236,7 @@ public class BasicOAuth2Store implements
 
     final String processedGadgetUri = this.getGadgetUri(gadgetUri, serviceName);
 
-    final Integer index = this.cache.getTokenIndex(processedGadgetUri, serviceName, user, scope,
-            type);
-    OAuth2Token token = this.cache.getToken(index);
+    OAuth2Token token = this.cache.getToken(processedGadgetUri, serviceName, user, scope, type);
     if (token == null) {
       try {
         token = this.persister.findToken(processedGadgetUri, serviceName, user, scope, type);
@@ -232,8 +244,7 @@ public class BasicOAuth2Store implements
           this.cache.storeToken(token);
         }
       } catch (final OAuth2PersistenceException e) {
-        throw new GadgetException(Code.OAUTH_STORAGE_ERROR, "Error loading OAuth2 token " + index,
-                e);
+        throw new GadgetException(Code.OAUTH_STORAGE_ERROR, "Error loading OAuth2 token", e);
       }
     }
 
@@ -250,6 +261,13 @@ public class BasicOAuth2Store implements
       BasicOAuth2Store.LOG.entering(BasicOAuth2Store.LOG_CLASS, "init");
     }
 
+    if (this.cache.isPrimed()) {
+      if (isLogging) {
+        BasicOAuth2Store.LOG.exiting(BasicOAuth2Store.LOG_CLASS, "init", false);
+      }
+      return false;
+    }
+
     this.clearCache();
 
     try {
@@ -288,9 +306,7 @@ public class BasicOAuth2Store implements
     final OAuth2Accessor ret = null;
 
     if (accessor != null) {
-      final Integer index = this.cache.getOAuth2AccessorIndex(accessor.getGadgetUri(),
-              accessor.getServiceName(), accessor.getUser(), accessor.getScope());
-      return this.cache.removeOAuth2Accessor(index);
+      return this.cache.removeOAuth2Accessor(accessor);
     }
 
     if (isLogging) {
@@ -333,17 +349,17 @@ public class BasicOAuth2Store implements
     }
 
     final String processedGadgetUri = this.getGadgetUri(gadgetUri, serviceName);
-
-    final Integer index = this.cache.getTokenIndex(processedGadgetUri, serviceName, user, scope,
-            type);
+    OAuth2Token token = this.getToken(processedGadgetUri, serviceName, user, scope, type);
     try {
-      final OAuth2Token token = this.cache.removeToken(index);
       if (token != null) {
-        this.persister.removeToken(processedGadgetUri, serviceName, user, scope, type);
-      }
+        token = this.cache.removeToken(token);
+        if (token != null) {
+          this.persister.removeToken(processedGadgetUri, serviceName, user, scope, type);
+        }
 
-      if (isLogging) {
-        BasicOAuth2Store.LOG.exiting(BasicOAuth2Store.LOG_CLASS, "removeToken", token);
+        if (isLogging) {
+          BasicOAuth2Store.LOG.exiting(BasicOAuth2Store.LOG_CLASS, "removeToken", token);
+        }
       }
 
       return token;
@@ -381,29 +397,26 @@ public class BasicOAuth2Store implements
 
       token.setGadgetUri(processedGadgetUri);
 
-      final Integer index = this.cache.getTokenIndex(token);
       final OAuth2Token existingToken = this.getToken(processedGadgetUri, token.getServiceName(),
               token.getUser(), token.getScope(), token.getType());
       try {
         if (existingToken == null) {
           this.persister.insertToken(token);
         } else {
-          this.cache.removeToken(index);
+          this.cache.removeToken(existingToken);
           this.persister.updateToken(token);
         }
         this.cache.storeToken(token);
       } catch (final OAuth2CacheException e) {
         if (isLogging) {
-          BasicOAuth2Store.LOG.log("Error storing OAuth2 token " + index, e);
+          BasicOAuth2Store.LOG.log("Error storing OAuth2 token", e);
         }
-        throw new GadgetException(Code.OAUTH_STORAGE_ERROR, "Error storing OAuth2 token " + index,
-                e);
+        throw new GadgetException(Code.OAUTH_STORAGE_ERROR, "Error storing OAuth2 token", e);
       } catch (final OAuth2PersistenceException e) {
         if (isLogging) {
-          BasicOAuth2Store.LOG.log("Error storing OAuth2 token " + index, e);
+          BasicOAuth2Store.LOG.log("Error storing OAuth2 token", e);
         }
-        throw new GadgetException(Code.OAUTH_STORAGE_ERROR, "Error storing OAuth2 token " + index,
-                e);
+        throw new GadgetException(Code.OAUTH_STORAGE_ERROR, "Error storing OAuth2 token", e);
       }
     }
 
@@ -437,4 +450,12 @@ public class BasicOAuth2Store implements
 
     return ret;
   }
+
+  protected OAuth2Token internalCreateToken() {
+    return new OAuth2TokenPersistence(this.encrypter);
+  }
+
+  public BlobCrypter getStateCrypter() {
+    return this.stateCrypter;
+  }
 }

Modified: shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2Accessor.java
URL: http://svn.apache.org/viewvc/shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2Accessor.java?rev=1336461&r1=1336460&r2=1336461&view=diff
==============================================================================
--- shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2Accessor.java (original)
+++ shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2Accessor.java Thu May 10 00:48:41 2012
@@ -1,26 +1,28 @@
 /*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with this
- * work for additional information regarding copyright ownership. The ASF
- * licenses this file to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
  *
- * http://www.apache.org/licenses/LICENSE-2.0
+ *   http://www.apache.org/licenses/LICENSE-2.0
  *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package org.apache.shindig.gadgets.oauth2;
 
+import org.apache.shindig.gadgets.oauth2.handler.ClientAuthenticationHandler;
+
 import java.io.Serializable;
 import java.util.Map;
 
-import org.apache.shindig.gadgets.oauth2.handler.ClientAuthenticationHandler;
-
 /**
  * OAuth2 related data accessor.
  *
@@ -45,85 +47,85 @@ public interface OAuth2Accessor extends 
    *
    * @return the access {@link OAuth2Token} or <code>null</code>
    */
-  public OAuth2Token getAccessToken();
+  OAuth2Token getAccessToken();
 
   /**
    *
    * @return the authorization endpoint for this accessor.
    */
-  public String getAuthorizationUrl();
+  String getAuthorizationUrl();
 
   /**
    * see {@link ClientAuthenticationHandler}
    *
    * @return the type of client authentication the service provider expects
    */
-  public String getClientAuthenticationType();
+  String getClientAuthenticationType();
 
   /**
    *
    * @return the "client_id" for this accessor
    */
-  public String getClientId();
+  String getClientId();
 
   /**
    *
    * @return the "client_secret" for this accessor
    */
-  public byte[] getClientSecret();
+  byte[] getClientSecret();
 
   /**
    *
    *
    */
-  public OAuth2Error getError();
+  OAuth2Error getError();
 
   /**
    *
    */
-  public String getErrorContextMessage();
+  String getErrorContextMessage();
 
   /**
    *
    * @return the error exception, if this is an error, otherwise <code>null</code>
    */
-  public Throwable getErrorException();
+  Throwable getErrorException();
 
   /**
    *
    * @return the error uri, if this is an error, otherwise <code>null</code>
    */
-  public String getErrorUri();
+  String getErrorUri();
 
   /**
    *
    * @return the URI of the gadget issuing the request
    */
-  public String getGadgetUri();
+  String getGadgetUri();
 
   /**
    *
    * @return grant_type of this client, e.g. "code" or "client_credentials"
    */
-  public String getGrantType();
+  String getGrantType();
 
   /**
    *
    * @return redirect_uri of the client for this accessor
    */
-  public String getRedirectUri();
+  String getRedirectUri();
 
   /**
    *
    * @return the refresh {@link OAuth2Token} or <code>null</code>
    */
-  public OAuth2Token getRefreshToken();
+  OAuth2Token getRefreshToken();
 
   /**
    *
    * @return the additional oauth2 request params (never <code>null</code>)
    */
-  public Map<String, String> getAdditionalRequestParams();
+  Map<String, String> getAdditionalRequestParams();
 
   /**
    * if the gadget request or gadget spec specifies a scope it will be set here
@@ -132,49 +134,49 @@ public interface OAuth2Accessor extends 
    *
    * @return scope of the request, or "" if none was specified
    */
-  public String getScope();
+  String getScope();
 
   /**
    *
    * @return the service name from the gadget spec, defaults to ""
    */
-  public String getServiceName();
+  String getServiceName();
 
   /**
    *
    * @return the state to include on authorization requests
    */
-  public String getState();
+  OAuth2CallbackState getState();
 
   /**
    *
    * @return the token endpoint for this accessor.
    */
-  public String getTokenUrl();
+  String getTokenUrl();
 
   /**
    *
    * @return the {@link Type} of client for this accessor
    */
-  public Type getType();
+  Type getType();
 
   /**
    *
    * @return of the page viewer
    */
-  public String getUser();
+  String getUser();
 
   /**
    * invalidates the accessor once the request is done.
    *
    */
-  public void invalidate();
+  void invalidate();
 
   /**
    *
    * @return <code>true</code> if the gadget's <ModulePrefs> can override accessor settings
    */
-  public boolean isAllowModuleOverrides();
+  boolean isAllowModuleOverrides();
 
   /**
    * Indicates the service provider wants the access token in an "Authorization:" header, per the
@@ -182,20 +184,20 @@ public interface OAuth2Accessor extends 
    *
    * @return
    */
-  public boolean isAuthorizationHeader();
+  boolean isAuthorizationHeader();
 
   /**
    *
    * @return if an error response needs to be sent to the client
    */
-  public boolean isErrorResponse();
+  boolean isErrorResponse();
 
   /**
    * is this accessor in the middle of a authorize redirect?
    *
    * @return
    */
-  public boolean isRedirecting();
+  boolean isRedirecting();
 
   /**
    * Indicates the service provider wants the access token in an URL Parameter. This goes against
@@ -203,23 +205,23 @@ public interface OAuth2Accessor extends 
    *
    * @return
    */
-  public boolean isUrlParameter();
+  boolean isUrlParameter();
 
-  public boolean isValid();
+  boolean isValid();
 
   /**
    * updates the access token for the request (does not add it to {@link OAuth2Store})
    *
    * @param accessToken
    */
-  public void setAccessToken(OAuth2Token accessToken);
+  void setAccessToken(OAuth2Token accessToken);
 
   /**
    * updates the authorization endpoint url
    *
    * @param authorizationUrl
    */
-  public void setAuthorizationUrl(String authorizationUrl);
+  void setAuthorizationUrl(String authorizationUrl);
 
   /**
    *
@@ -228,7 +230,7 @@ public interface OAuth2Accessor extends 
    * @param contextMessage
    * @param errorUri
    */
-  public void setErrorResponse(Throwable exception, OAuth2Error error, String contextMessage,
+  void setErrorResponse(Throwable exception, OAuth2Error error, String contextMessage,
           String errorUri);
 
   /**
@@ -237,26 +239,40 @@ public interface OAuth2Accessor extends 
    *
    * @param redirecting
    */
-  public void setRedirecting(boolean redirecting);
+  void setRedirecting(boolean redirecting);
 
   /**
    * updates the refresh token for the request (does not add it to {@link OAuth2Store})
    *
    * @param accessToken
    */
-  public void setRefreshToken(OAuth2Token refreshToken);
+  void setRefreshToken(OAuth2Token refreshToken);
 
   /**
    * set the oauth2 request parameters
    *
    * @param requestParams
    */
-  public void setAdditionalRequestParams(Map<String, String> requestParams);
+  void setAdditionalRequestParams(Map<String, String> requestParams);
 
   /**
    * updates the token endpoint url
    *
    * @param tokenUrl
    */
-  public void setTokenUrl(String tokenUrl);
+  void setTokenUrl(String tokenUrl);
+
+  /**
+   * sets the domains of allowed resource servers
+   *
+   * @param allowedDomains
+   */
+  void setAllowedDomains(String[] allowedDomains);
+
+  /**
+   * gets the domains of allowed resource servers
+   *
+   * @return allowed domains, may be empty but never <code>null</code>
+   */
+  String[] getAllowedDomains();
 }

Added: shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2CallbackState.java
URL: http://svn.apache.org/viewvc/shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2CallbackState.java?rev=1336461&view=auto
==============================================================================
--- shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2CallbackState.java (added)
+++ shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2CallbackState.java Thu May 10 00:48:41 2012
@@ -0,0 +1,115 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.shindig.gadgets.oauth2;
+
+import com.google.common.collect.Maps;
+
+import org.apache.shindig.common.crypto.BlobCrypter;
+import org.apache.shindig.common.crypto.BlobCrypterException;
+import org.apache.shindig.gadgets.oauth2.logger.FilteredLogger;
+
+import java.io.Serializable;
+import java.util.Map;
+
+public class OAuth2CallbackState implements Serializable {
+  private static final long serialVersionUID = 6591011719613609006L;
+  private static final String LOG_CLASS = OAuth2CallbackState.class.getName();
+  private static final FilteredLogger LOG = FilteredLogger
+          .getFilteredLogger(OAuth2CallbackState.LOG_CLASS);
+
+  private final transient BlobCrypter crypter;
+  private OAuth2CallbackStateToken state;
+
+  public OAuth2CallbackState() {
+    this(null);
+  }
+
+  public OAuth2CallbackState(final BlobCrypter crypter) {
+    this.crypter = crypter;
+    this.state = new OAuth2CallbackStateToken();
+  }
+
+  public OAuth2CallbackState(final BlobCrypter crypter, final String stateBlob) {
+    this.crypter = crypter;
+
+    Map<String, String> state = null;
+    if (stateBlob != null && crypter != null) {
+      try {
+        state = crypter.unwrap(stateBlob);
+
+        if (state == null) {
+          state = Maps.newHashMap();
+        }
+        this.state = new OAuth2CallbackStateToken(state);
+        this.state.enforceNotExpired();
+      } catch (final BlobCrypterException e) {
+        // Too old, or corrupt. Ignore it.
+        state = null;
+        if (OAuth2CallbackState.LOG.isLoggable()) {
+          OAuth2CallbackState.LOG.log("OAuth2CallbackState stateBlob decryption failed", e);
+        }
+      }
+    }
+    if (state == null) {
+      this.state = new OAuth2CallbackStateToken();
+    }
+  }
+
+  public String getEncryptedState() throws BlobCrypterException {
+    String ret = null;
+    if (this.crypter != null) {
+      ret = this.crypter.wrap(this.state.toMap());
+    }
+    
+    return ret;
+  }
+
+  public String getGadgetUri() {
+    return this.state.getGadgetUri();
+  }
+
+  public void setGadgetUri(final String gadgetUri) {
+    this.state.setGadgetUri(gadgetUri);
+  }
+
+  public String getServiceName() {
+    return this.state.getServiceName();
+  }
+
+  public void setServiceName(final String serviceName) {
+    this.state.setServiceName(serviceName);
+  }
+
+  public String getUser() {
+    return this.state.getUser();
+  }
+
+  public void setUser(final String user) {
+    this.state.setUser(user);
+  }
+
+  public String getScope() {
+    return this.state.getScope();
+  }
+
+  public void setScope(final String scope) {
+    this.state.setScope(scope);
+  }
+}

Propchange: shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2CallbackState.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2CallbackStateToken.java
URL: http://svn.apache.org/viewvc/shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2CallbackStateToken.java?rev=1336461&view=auto
==============================================================================
--- shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2CallbackStateToken.java (added)
+++ shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2CallbackStateToken.java Thu May 10 00:48:41 2012
@@ -0,0 +1,163 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.shindig.gadgets.oauth2;
+
+import org.apache.shindig.auth.AbstractSecurityToken;
+
+import java.io.Serializable;
+import java.util.EnumSet;
+import java.util.Map;
+
+/**
+ *
+ */
+public class OAuth2CallbackStateToken extends AbstractSecurityToken implements Serializable {
+  private static final long serialVersionUID = -3913197153778386101L;
+  private static final EnumSet<Keys> MAP_KEYS = EnumSet.of(Keys.EXPIRES);
+  private static final String GADGET_URI = "g";
+  private static final String SERVICE_NAME = "sn";
+  private static final String USER = "u";
+  private static final String SCOPE = "sc";
+
+  private String gadgetUri;
+  private String serviceName;
+  private String user;
+  private String scope;
+
+  OAuth2CallbackStateToken() {
+    // used by OAuth2CallbackState
+  }
+
+  public OAuth2CallbackStateToken(final Map<String, String> values) {
+    this.loadFromMap(values);
+  }
+
+  @Override
+  protected AbstractSecurityToken loadFromMap(final Map<String, String> map) {
+    super.loadFromMap(map);
+    final String g = map.get(OAuth2CallbackStateToken.GADGET_URI);
+    if (g != null) {
+      this.setGadgetUri(g);
+    }
+
+    final String sn = map.get(OAuth2CallbackStateToken.SERVICE_NAME);
+    if (sn != null) {
+      this.setServiceName(sn);
+    }
+
+    final String u = map.get(OAuth2CallbackStateToken.USER);
+    if (u != null) {
+      this.setUser(u);
+    }
+
+    final String sc = map.get(OAuth2CallbackStateToken.SCOPE);
+    if (sc != null) {
+      this.setScope(sc);
+    }
+
+    return this;
+  }
+
+  public String getUpdatedToken() {
+    return null;
+  }
+
+  public String getAuthenticationMode() {
+    return null;
+  }
+
+  public boolean isAnonymous() {
+    return false;
+  }
+
+  @Override
+  protected EnumSet<Keys> getMapKeys() {
+    return OAuth2CallbackStateToken.MAP_KEYS;
+  }
+
+  public String getGadgetUri() {
+    return this.gadgetUri;
+  }
+
+  public String getServiceName() {
+    return this.serviceName;
+  }
+
+  public String getUser() {
+    return this.user;
+  }
+
+  public String getScope() {
+    return this.scope;
+  }
+
+  public OAuth2CallbackStateToken setGadgetUri(final String gadgetUri) {
+    this.gadgetUri = gadgetUri;
+    return this;
+  }
+
+  public OAuth2CallbackStateToken setServiceName(final String serviceName) {
+    this.serviceName = serviceName;
+    return this;
+  }
+
+  public OAuth2CallbackStateToken setUser(final String user) {
+    this.user = user;
+    return this;
+  }
+
+  public OAuth2CallbackStateToken setScope(final String scope) {
+    this.scope = scope;
+    return this;
+  }
+
+  /**
+   * Returns token time to live in seconds.
+   */
+  @Override
+  protected int getMaxTokenTTL() {
+    return 600;
+  }
+
+  @Override
+  public Map<String, String> toMap() {
+    final Map<String, String> map = super.toMap();
+    final String g = this.getGadgetUri();
+    if (g != null) {
+      map.put(OAuth2CallbackStateToken.GADGET_URI, g);
+    }
+
+    final String sn = this.getServiceName();
+    if (sn != null) {
+      map.put(OAuth2CallbackStateToken.SERVICE_NAME, sn);
+    }
+
+    final String u = this.getUser();
+    if (u != null) {
+      map.put(OAuth2CallbackStateToken.USER, u);
+    }
+
+    final String sc = this.getScope();
+    if (sc != null) {
+      map.put(OAuth2CallbackStateToken.SCOPE, sc);
+    }
+
+    return map;
+  }
+}

Propchange: shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2CallbackStateToken.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Modified: shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2Error.java
URL: http://svn.apache.org/viewvc/shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2Error.java?rev=1336461&r1=1336460&r2=1336461&view=diff
==============================================================================
--- shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2Error.java (original)
+++ shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2Error.java Thu May 10 00:48:41 2012
@@ -1,29 +1,30 @@
 /*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with this
- * work for additional information regarding copyright ownership. The ASF
- * licenses this file to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
  *
- * http://www.apache.org/licenses/LICENSE-2.0
+ *   http://www.apache.org/licenses/LICENSE-2.0
  *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package org.apache.shindig.gadgets.oauth2;
 
+import org.apache.shindig.gadgets.oauth2.logger.FilteredLogger;
+
 import java.text.MessageFormat;
 import java.util.ResourceBundle;
 
-import org.apache.shindig.gadgets.oauth2.logger.FilteredLogger;
-
 /**
- * Any time there's an error in the OAuth2 layer it's reported with an
- * OAuth2Error.
+ * Any time there's an error in the OAuth2 layer it's reported with an OAuth2Error.
  *
  * errorCode - should correspond to an OAuth2Message errorCode when appropriate.
  *
@@ -31,7 +32,7 @@ import org.apache.shindig.gadgets.oauth2
 public enum OAuth2Error {
   AUTHORIZATION_CODE_PROBLEM("authorization_code_problem"),
   AUTHORIZE_PROBLEM("authorize_problem"),
-  AUTHENTICATION_PROBLEM( "authentication_problem"),
+  AUTHENTICATION_PROBLEM("authentication_problem"),
   BEARER_TOKEN_PROBLEM("bearer_token_problem"),
   CALLBACK_PROBLEM("callback_problem"),
   CLIENT_CREDENTIALS_PROBLEM("client_credentials_problem"),
@@ -73,46 +74,46 @@ public enum OAuth2Error {
   private OAuth2Error(final String errorCode) {
     this.errorCode = errorCode;
     String header = OAuth2Request.class.getName() + " encountered a problem: ";
-    String _errorDescription = errorCode;
-    String _errorExplanation = errorCode;
+    String eDescription = errorCode;
+    String eExplanation = errorCode;
 
-    FilteredLogger LOG = null;
+    FilteredLogger log = null;
     try {
-      LOG = FilteredLogger.getFilteredLogger(OAuth2Error.class.getName());
-      final ResourceBundle resourceBundle = LOG.getResourceBundle();
+      log = FilteredLogger.getFilteredLogger("org.apache.shindig.gadgets.oauth2.OAuth2Error");
+      final ResourceBundle resourceBundle = log.getResourceBundle();
       if (resourceBundle != null) {
-        final String bundleHeader = resourceBundle.getString(OAuth2Error.MESSAGE_HEADER);
+        final String bundleHeader = resourceBundle.getString("message_header");
         if (bundleHeader != null) {
           header = MessageFormat.format(bundleHeader, OAuth2Request.class.getName());
         }
 
         final String bundleErrorDescription = resourceBundle.getString(this.errorCode);
         if ((bundleErrorDescription == null) || (bundleErrorDescription.length() == 0)) {
-          _errorDescription = header + this.errorCode;
+          eDescription = header + this.errorCode;
         } else {
-          _errorDescription = header + bundleErrorDescription;
+          eDescription = header + bundleErrorDescription;
         }
 
         final String bundleErrorExplanation = resourceBundle.getString(this.errorCode
-            + ".explanation");
+                + ".explanation");
         if ((bundleErrorExplanation == null) || (bundleErrorExplanation.length() == 0)) {
-          _errorExplanation = _errorDescription;
+          eExplanation = eDescription;
         } else {
-          _errorExplanation = bundleErrorExplanation;
+          eExplanation = bundleErrorExplanation;
         }
       }
     } catch (final Exception e) {
-      if (LOG != null) {
-        if (LOG.isLoggable()) {
-          LOG.log("error loading OAuth2Error messages", e);
+      if (log != null) {
+        if (log.isLoggable()) {
+          log.log("error loading OAuth2Error messages", e);
         }
       } else {
         e.printStackTrace();
       }
     }
 
-    this.errorDescription = _errorDescription;
-    this.errorExplanation = _errorExplanation;
+    this.errorDescription = eDescription;
+    this.errorExplanation = eExplanation;
   }
 
   public String getErrorCode() {

Modified: shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2FetcherConfig.java
URL: http://svn.apache.org/viewvc/shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2FetcherConfig.java?rev=1336461&r1=1336460&r2=1336461&view=diff
==============================================================================
--- shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2FetcherConfig.java (original)
+++ shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2FetcherConfig.java Thu May 10 00:48:41 2012
@@ -1,18 +1,20 @@
 /*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with this
- * work for additional information regarding copyright ownership. The ASF
- * licenses this file to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
  *
- * http://www.apache.org/licenses/LICENSE-2.0
+ *   http://www.apache.org/licenses/LICENSE-2.0
  *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package org.apache.shindig.gadgets.oauth2;
 
@@ -25,10 +27,12 @@ import com.google.inject.name.Named;
 public class OAuth2FetcherConfig {
   private final GadgetOAuth2TokenStore tokenStore;
   private final boolean viewerAccessTokensEnabled;
+  public static final String OAUTH2_STATE_CRYPTER = "shindig.oauth2.state-crypter";
 
   @Inject
   public OAuth2FetcherConfig(final GadgetOAuth2TokenStore tokenStore,
-      @Named("shindig.oauth2.viewer-access-tokens-enabled") final boolean viewerAccessTokensEnabled) {
+          @Named("shindig.oauth2.viewer-access-tokens-enabled")
+          final boolean viewerAccessTokensEnabled) {
     this.tokenStore = tokenStore;
     this.viewerAccessTokensEnabled = viewerAccessTokensEnabled;
   }

Modified: shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2Message.java
URL: http://svn.apache.org/viewvc/shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2Message.java?rev=1336461&r1=1336460&r2=1336461&view=diff
==============================================================================
--- shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2Message.java (original)
+++ shindig/trunk/java/gadgets/src/main/java/org/apache/shindig/gadgets/oauth2/OAuth2Message.java Thu May 10 00:48:41 2012
@@ -1,18 +1,20 @@
 /*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with this
- * work for additional information regarding copyright ownership. The ASF
- * licenses this file to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package org.apache.shindig.gadgets.oauth2;
 
@@ -22,161 +24,158 @@ import javax.servlet.http.HttpServletReq
 
 /**
  *
- * Interface representing an OAuth2Message parser that is injected into the
- * {@link OAuth2Request} layer.
+ * Interface representing an OAuth2Message parser that is injected into the {@link OAuth2Request}
+ * layer.
  *
  * It also contains the OAuth 2.0 constants.
  *
- * With the simplicity of the OAuth 2.0 client it is unlikely that another
- * version of this class will need to be injected, but it can be with
+ * With the simplicity of the OAuth 2.0 client it is unlikely that another version of this class
+ * will need to be injected, but it can be with
  * <code>com.google.inject.Provider<OAuth2Message></code>
  *
  */
 public interface OAuth2Message {
-  public final static String ACCESS_DENIED = "access_denied";
-  public final static String ACCESS_TOKEN = "access_token";
-  public final static String AUTHORIZATION = "code";
-  public final static String AUTHORIZATION_CODE = "authorization_code";
-  public final static String AUTHORIZATION_HEADER = "Authorization";
-  public final static String BASIC_AUTH_TYPE = "Basic";
-  public final static String BEARER_TOKEN_TYPE = "Bearer";
-  public final static String BODYHASH = "bodyhash";
-  public final static String CLIENT_CREDENTIALS = "client_credentials";
-  public final static String CLIENT_ID = "client_id";
-  public final static String CLIENT_SECRET = "client_secret";
-  public final static String CONFIDENTIAL_CLIENT_TYPE = "confidential";
-  public final static String ERROR = "error";
-  public final static String ERROR_DESCRIPTION = "error_description";
-  public final static String ERROR_URI = "error_uri";
-  public final static String EXPIRES_IN = "expires_in";
-  public final static String GRANT_TYPE = "grant_type";
-  public final static String HMAC_SHA_1 = "hmac-sha-1";
-  public final static String HMAC_SHA_256 = "hmac-sha-256";
-  public final static String ID = "id";
-  public final static String INVALID_CLIENT = "invalid_client";
-  public final static String INVALID_GRANT = "invalid_grant";
-  public final static String INVALID_REQUEST = "invalid_request";
-  public final static String INVALID_SCOPE = "invalid_scope";
-  public final static String MAC = "mac";
-  public final static String MAC_ALGORITHM = "algorithm";
-  public final static String MAC_EXT = "ext";
-  public final static String MAC_HEADER = "MAC";
-  public final static String MAC_SECRET = "secret";
-  public final static String MAC_TOKEN_TYPE = "mac";
-  public final static String NO_GRANT_TYPE = "NONE";
-  public final static String NONCE = "nonce";
-  public final static String PUBLIC_CLIENT_TYPE = "public";
-  public final static String REDIRECT_URI = "redirect_uri";
-  public final static String REFRESH_TOKEN = "refresh_token";
-  public final static String RESPONSE_TYPE = "response_type";
-  public final static String SCOPE = "scope";
-  public final static String SERVER_ERROR = "server_error";
-  public final static String SHARED_TOKEN = "sharedToken";
-  public final static String STANDARD_AUTH_TYPE = "STANDARD";
-  public final static String STATE = "state";
-  public final static String TEMPORARILY_UNAVAILABLE = "temporarily_unavailable";
-  public final static String TOKEN_RESPONSE = "token";
-  public final static String TOKEN_TYPE = "token_type";
-  public final static String UNAUTHORIZED_CLIENT = "authorized_client";
-  public final static String UNSUPPORTED_GRANT_TYPE = "unsupported_grant_type";
-  public final static String UNSUPPORTED_RESPONSE_TYPE = "unsupported_response_type";
+  String ACCESS_DENIED = "access_denied";
+  String ACCESS_TOKEN = "access_token";
+  String AUTHORIZATION = "code";
+  String AUTHORIZATION_CODE = "authorization_code";
+  String AUTHORIZATION_HEADER = "Authorization";
+  String BASIC_AUTH_TYPE = "Basic";
+  String BEARER_TOKEN_TYPE = "Bearer";
+  String BODYHASH = "bodyhash";
+  String CLIENT_CREDENTIALS = "client_credentials";
+  String CLIENT_ID = "client_id";
+  String CLIENT_SECRET = "client_secret";
+  String CONFIDENTIAL_CLIENT_TYPE = "confidential";
+  String ERROR = "error";
+  String ERROR_DESCRIPTION = "error_description";
+  String ERROR_URI = "error_uri";
+  String EXPIRES_IN = "expires_in";
+  String GRANT_TYPE = "grant_type";
+  String HMAC_SHA_1 = "hmac-sha-1";
+  String HMAC_SHA_256 = "hmac-sha-256";
+  String ID = "id";
+  String INVALID_CLIENT = "invalid_client";
+  String INVALID_GRANT = "invalid_grant";
+  String INVALID_REQUEST = "invalid_request";
+  String INVALID_SCOPE = "invalid_scope";
+  String MAC = "mac";
+  String MAC_ALGORITHM = "algorithm";
+  String MAC_EXT = "ext";
+  String MAC_HEADER = "MAC";
+  String MAC_SECRET = "secret";
+  String MAC_TOKEN_TYPE = "mac";
+  String NO_GRANT_TYPE = "NONE";
+  String NONCE = "nonce";
+  String PUBLIC_CLIENT_TYPE = "public";
+  String REDIRECT_URI = "redirect_uri";
+  String REFRESH_TOKEN = "refresh_token";
+  String RESPONSE_TYPE = "response_type";
+  String SCOPE = "scope";
+  String SERVER_ERROR = "server_error";
+  String SHARED_TOKEN = "sharedToken";
+  String STANDARD_AUTH_TYPE = "STANDARD";
+  String STATE = "state";
+  String TEMPORARILY_UNAVAILABLE = "temporarily_unavailable";
+  String TOKEN_RESPONSE = "token";
+  String TOKEN_TYPE = "token_type";
+  String UNAUTHORIZED_CLIENT = "authorized_client";
+  String UNSUPPORTED_GRANT_TYPE = "unsupported_grant_type";
+  String UNSUPPORTED_RESPONSE_TYPE = "unsupported_response_type";
 
   /**
    * After a message is parsed it may contain an access token.
    *
    * @return the access_token in the message
    */
-  public String getAccessToken();
+  String getAccessToken();
 
   /**
-   * If this is an Authorization Code flow this method will return the
-   * authorization_code from the message.
+   * If this is an Authorization Code flow this method will return the authorization_code from the
+   * message.
    *
    * @return authorization_code in the message
    */
-  public String getAuthorization();
+  String getAuthorization();
 
   /**
-   * <code>null</code> error indicates the message parsed cleanly and the
-   * service provider did not return an error.
+   * <code>null</code> error indicates the message parsed cleanly and the service provider did not
+   * return an error.
    *
    * @return the error from the service provider
    */
-  public OAuth2Error getError();
+  OAuth2Error getError();
 
   /**
    *
    * @return the optional error_description from the service provider
    */
-  public String getErrorDescription();
+  String getErrorDescription();
 
   /**
    *
    * @return the optional error_uri from the service provider
    */
-  public String getErrorUri();
+  String getErrorUri();
 
   /**
    *
    * @return "expires_in" parameter in the message
    */
-  public String getExpiresIn();
+  String getExpiresIn();
 
   /**
-   * The MAC Algorithm
-   * http://tools.ietf.org/html/draft-hammer-oauth-v2-mac-token-05#section-5
+   * The MAC Algorithm http://tools.ietf.org/html/draft-hammer-oauth-v2-mac-token-05#section-5
    *
    * @return
    */
-  public String getMacAlgorithm();
+  String getMacAlgorithm();
 
   /**
-   * The MAC Secret
-   * http://tools.ietf.org/html/draft-hammer-oauth-v2-mac-token-05#section-5
+   * The MAC Secret http://tools.ietf.org/html/draft-hammer-oauth-v2-mac-token-05#section-5
    *
    * @return
    */
-  public String getMacSecret();
+  String getMacSecret();
 
   /**
    *
    * @return a general {@link Map} of all parameters in the message
    */
-  public Map<String, String> getParameters();
+  Map<String, String> getParameters();
 
   /**
    *
    * @return the "refresh_token" in the message
    */
-  public String getRefreshToken();
+  String getRefreshToken();
 
   /**
    *
    * @return the optional state string in the message
    */
-  public String getState();
+  String getState();
 
   /**
    *
    * @return the "token_type" type in the message
    */
-  public String getTokenType();
+  String getTokenType();
 
   /**
-   * Additional properties that went unparsed (i.e. aren't part of the core
-   * OAuth2, Bearer Token or MAC Token specs.
+   * Additional properties that went unparsed (i.e. aren't part of the core OAuth2, Bearer Token or
+   * MAC Token specs.
    *
    * @return
    */
-  public Map<String, String> getUnparsedProperties();
+  Map<String, String> getUnparsedProperties();
 
   /**
-   * Populates an OAuth2Message from a query fragment. Not very useful in
-   * shindig.
+   * Populates an OAuth2Message from a query fragment. Not very useful in shindig.
    *
    * @param fragment
    */
-  public void parseFragment(String fragment);
+  void parseFragment(String fragment);
 
   /**
    * Populates an OAuth2Message from a JSON response body.
@@ -184,7 +183,7 @@ public interface OAuth2Message {
    * @param jsonString
    *          returned from token endpoint request
    */
-  public void parseJSON(String jsonString);
+  void parseJSON(String jsonString);
 
   /**
    * Populates an OAuth2Message from a URL query string.
@@ -192,7 +191,7 @@ public interface OAuth2Message {
    * @param queryString
    *          from redirect_uri called by servcie provider
    */
-  public void parseQuery(String queryString);
+  void parseQuery(String queryString);
 
   /**
    * Populates an OAuth2Message from the entire {@link HttpServletRequest}
@@ -201,23 +200,23 @@ public interface OAuth2Message {
    * @param request
    *          to parse
    */
-  public void parseRequest(HttpServletRequest request);
+  void parseRequest(HttpServletRequest request);
 
   /**
    *
    * @param error
    */
-  public void setError(OAuth2Error error);
+  void setError(OAuth2Error error);
 
   /**
    *
    * @param errorDescription
    */
-  public void setErrorDescription(String errorDescription);
+  void setErrorDescription(String errorDescription);
 
   /**
    *
    * @param errorUri
    */
-  public void setErrorUri(String errorUri);
+  void setErrorUri(String errorUri);
 }