You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@chemistry.apache.org by fm...@apache.org on 2013/12/28 16:51:48 UTC
svn commit: r1553852 - in /chemistry/opencmis/trunk:
chemistry-opencmis-client/chemistry-opencmis-client-api/src/main/java/org/apache/chemistry/opencmis/client/
chemistry-opencmis-client/chemistry-opencmis-client-bindings/src/main/java/org/apache/chemi...
Author: fmui
Date: Sat Dec 28 15:51:47 2013
New Revision: 1553852
URL: http://svn.apache.org/r1553852
Log:
OAuth improvements
Modified:
chemistry/opencmis/trunk/chemistry-opencmis-client/chemistry-opencmis-client-api/src/main/java/org/apache/chemistry/opencmis/client/SessionParameterMap.java
chemistry/opencmis/trunk/chemistry-opencmis-client/chemistry-opencmis-client-bindings/src/main/java/org/apache/chemistry/opencmis/client/bindings/spi/AbstractAuthenticationProvider.java
chemistry/opencmis/trunk/chemistry-opencmis-client/chemistry-opencmis-client-bindings/src/main/java/org/apache/chemistry/opencmis/client/bindings/spi/OAuthAuthenticationProvider.java
chemistry/opencmis/trunk/chemistry-opencmis-commons/chemistry-opencmis-commons-api/src/main/java/org/apache/chemistry/opencmis/commons/SessionParameter.java
Modified: chemistry/opencmis/trunk/chemistry-opencmis-client/chemistry-opencmis-client-api/src/main/java/org/apache/chemistry/opencmis/client/SessionParameterMap.java
URL: http://svn.apache.org/viewvc/chemistry/opencmis/trunk/chemistry-opencmis-client/chemistry-opencmis-client-api/src/main/java/org/apache/chemistry/opencmis/client/SessionParameterMap.java?rev=1553852&r1=1553851&r2=1553852&view=diff
==============================================================================
--- chemistry/opencmis/trunk/chemistry-opencmis-client/chemistry-opencmis-client-api/src/main/java/org/apache/chemistry/opencmis/client/SessionParameterMap.java (original)
+++ chemistry/opencmis/trunk/chemistry-opencmis-client/chemistry-opencmis-client-api/src/main/java/org/apache/chemistry/opencmis/client/SessionParameterMap.java Sat Dec 28 15:51:47 2013
@@ -254,9 +254,9 @@ public class SessionParameterMap extends
*/
public void setBearerToken(String token) {
if (token == null) {
- remove(SessionParameter.BREARER_ACCESS_TOKEN);
+ remove(SessionParameter.OAUTH_ACCESS_TOKEN);
} else {
- put(SessionParameter.BREARER_ACCESS_TOKEN, token);
+ put(SessionParameter.OAUTH_ACCESS_TOKEN, token);
}
}
@@ -363,7 +363,7 @@ public class SessionParameterMap extends
put(SessionParameter.AUTH_HTTP_BASIC, false);
put(SessionParameter.AUTH_SOAP_USERNAMETOKEN, false);
put(SessionParameter.AUTH_OAUTH_BEARER, true);
- put(SessionParameter.BREARER_ACCESS_TOKEN, token);
+ put(SessionParameter.OAUTH_ACCESS_TOKEN, token);
remove(SessionParameter.AUTHENTICATION_PROVIDER_CLASS);
}
@@ -372,7 +372,8 @@ public class SessionParameterMap extends
* Turns OAuth 2.0 authentication on and basic authentication and
* UsernameToken authentication off.
* <p>
- * This authentication method refreshes the token when it expires.
+ * This authentication method requests a new token and refreshes the token
+ * when it expires.
*
* @param tokenEntpoint
* the token endpoint URL
@@ -383,25 +384,24 @@ public class SessionParameterMap extends
* @param code
* the authorization code
* @param redirectUri
- * the redirect URI
+ * the redirect URI if required, {@code null} otherwise
*/
public void setOAuthAuthentication(String tokenEntpoint, String clientId, String clientSecret, String code,
String redirectUri) {
- if (tokenEntpoint == null) {
+ if (tokenEntpoint == null || tokenEntpoint.length() == 0) {
throw new IllegalArgumentException("Token endpoint must be set!");
}
+ if (clientId == null || clientId.length() == 0) {
+ throw new IllegalArgumentException("Client ID must be set!");
+ }
+
put(SessionParameter.AUTH_HTTP_BASIC, false);
put(SessionParameter.AUTH_SOAP_USERNAMETOKEN, false);
put(SessionParameter.AUTH_OAUTH_BEARER, false);
put(SessionParameter.OAUTH_TOKEN_ENDPOINT, tokenEntpoint);
-
- if (clientId == null) {
- remove(SessionParameter.OAUTH_CLIENT_ID);
- } else {
- put(SessionParameter.OAUTH_CLIENT_ID, clientId);
- }
+ put(SessionParameter.OAUTH_CLIENT_ID, clientId);
if (clientSecret == null) {
remove(SessionParameter.OAUTH_CLIENT_SECRET);
@@ -426,6 +426,71 @@ public class SessionParameterMap extends
}
/**
+ * Turns OAuth 2.0 authentication on and basic authentication and
+ * UsernameToken authentication off.
+ * <p>
+ * This authentication method uses the provided token and refreshes the
+ * token when it expires.
+ *
+ * @param tokenEntpoint
+ * the token endpoint URL
+ * @param clientId
+ * the client ID
+ * @param clientSecret
+ * the client secret if required, {@code null} otherwise
+ * @param accessToken
+ * the bearer access token
+ * @param refreshToken
+ * the refresh token
+ * @param expirationTimestamp
+ * the timestamp when the access token expires
+ */
+ public void setOAuthAuthentication(String tokenEntpoint, String clientId, String clientSecret, String accessToken,
+ String refreshToken, long expirationTimestamp) {
+ if (tokenEntpoint == null || tokenEntpoint.length() == 0) {
+ throw new IllegalArgumentException("Token endpoint must be set!");
+ }
+
+ if (clientId == null || clientId.length() == 0) {
+ throw new IllegalArgumentException("Client ID must be set!");
+ }
+
+ put(SessionParameter.AUTH_HTTP_BASIC, false);
+ put(SessionParameter.AUTH_SOAP_USERNAMETOKEN, false);
+ put(SessionParameter.AUTH_OAUTH_BEARER, false);
+
+ put(SessionParameter.OAUTH_TOKEN_ENDPOINT, tokenEntpoint);
+ put(SessionParameter.OAUTH_CLIENT_ID, clientId);
+
+ if (clientSecret == null) {
+ remove(SessionParameter.OAUTH_CLIENT_SECRET);
+ } else {
+ put(SessionParameter.OAUTH_CLIENT_SECRET, clientSecret);
+ }
+
+ if (accessToken == null) {
+ remove(SessionParameter.OAUTH_ACCESS_TOKEN);
+ } else {
+ put(SessionParameter.OAUTH_ACCESS_TOKEN, accessToken);
+ }
+
+ if (refreshToken == null) {
+ remove(SessionParameter.OAUTH_REFRESH_TOKEN);
+ } else {
+ put(SessionParameter.OAUTH_REFRESH_TOKEN, refreshToken);
+ }
+
+ if (expirationTimestamp < 0) {
+ remove(SessionParameter.OAUTH_EXPIRATION_TIMESTAMP);
+ } else {
+ put(SessionParameter.OAUTH_EXPIRATION_TIMESTAMP, expirationTimestamp);
+ }
+
+ put(SessionParameter.AUTHENTICATION_PROVIDER_CLASS,
+ "org.apache.chemistry.opencmis.client.bindings.spi.OAuthAuthenticationProvider");
+ }
+
+ /**
* Sets the locale of the session.
*
* @param locale
Modified: chemistry/opencmis/trunk/chemistry-opencmis-client/chemistry-opencmis-client-bindings/src/main/java/org/apache/chemistry/opencmis/client/bindings/spi/AbstractAuthenticationProvider.java
URL: http://svn.apache.org/viewvc/chemistry/opencmis/trunk/chemistry-opencmis-client/chemistry-opencmis-client-bindings/src/main/java/org/apache/chemistry/opencmis/client/bindings/spi/AbstractAuthenticationProvider.java?rev=1553852&r1=1553851&r2=1553852&view=diff
==============================================================================
--- chemistry/opencmis/trunk/chemistry-opencmis-client/chemistry-opencmis-client-bindings/src/main/java/org/apache/chemistry/opencmis/client/bindings/spi/AbstractAuthenticationProvider.java (original)
+++ chemistry/opencmis/trunk/chemistry-opencmis-client/chemistry-opencmis-client-bindings/src/main/java/org/apache/chemistry/opencmis/client/bindings/spi/AbstractAuthenticationProvider.java Sat Dec 28 15:51:47 2013
@@ -108,7 +108,7 @@ public abstract class AbstractAuthentica
* @return the bearer token or {@code null} if the token is not set
*/
protected String getBearerToken() {
- Object tokenObject = getSession().get(SessionParameter.BREARER_ACCESS_TOKEN);
+ Object tokenObject = getSession().get(SessionParameter.OAUTH_ACCESS_TOKEN);
if (tokenObject instanceof String) {
return (String) tokenObject;
}
Modified: chemistry/opencmis/trunk/chemistry-opencmis-client/chemistry-opencmis-client-bindings/src/main/java/org/apache/chemistry/opencmis/client/bindings/spi/OAuthAuthenticationProvider.java
URL: http://svn.apache.org/viewvc/chemistry/opencmis/trunk/chemistry-opencmis-client/chemistry-opencmis-client-bindings/src/main/java/org/apache/chemistry/opencmis/client/bindings/spi/OAuthAuthenticationProvider.java?rev=1553852&r1=1553851&r2=1553852&view=diff
==============================================================================
--- chemistry/opencmis/trunk/chemistry-opencmis-client/chemistry-opencmis-client-bindings/src/main/java/org/apache/chemistry/opencmis/client/bindings/spi/OAuthAuthenticationProvider.java (original)
+++ chemistry/opencmis/trunk/chemistry-opencmis-client/chemistry-opencmis-client-bindings/src/main/java/org/apache/chemistry/opencmis/client/bindings/spi/OAuthAuthenticationProvider.java Sat Dec 28 15:51:47 2013
@@ -42,7 +42,63 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * OAuth Authentication Provider.
+ * OAuth 2.0 Authentication Provider.
+ * <p>
+ * This authentication provider implements OAuth 2.0 (RFC 6749) Bearer Tokens
+ * (RFC 6750).
+ * <p>
+ * The provider can be either configured with an authorization code or with an
+ * existing bearer token. Token endpoint and client ID are always required. If a
+ * client secret is required depends on the authorization server.
+ * <p>
+ * Configuration with authorization code:
+ *
+ * <pre>
+ * SessionFactory factory = ...
+ *
+ * Map<String, String> parameter = new HashMap<String, String>();
+ *
+ * parameter.put(SessionParameter.ATOMPUB_URL, "http://localhost/cmis/atom");
+ * parameter.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value());
+ * parameter.put(SessionParameter.REPOSITORY_ID, "myRepository");
+ *
+ * parameter.put(SessionParameter.AUTHENTICATION_PROVIDER_CLASS, "org.apache.chemistry.opencmis.client.bindings.spi.OAuthAuthenticationProvider");
+ *
+ * parameter.put(SessionParameter.OAUTH_TOKEN_ENDPOINT, "https://example.com/auth/oauth/token");
+ * parameter.put(SessionParameter.OAUTH_CLIENT_ID, "s6BhdRkqt3");
+ * parameter.put(SessionParameter.OAUTH_CLIENT_SECRET, "7Fjfp0ZBr1KtDRbnfVdmIw");
+ *
+ * parameter.put(SessionParameter.OAUTH_CODE, "abc");
+ *
+ * ...
+ * Session session = factory.createSession(parameter);
+ * </pre>
+ *
+ * <p>
+ * Configuration with existing bearer token:
+ *
+ * <pre>
+ * SessionFactory factory = ...
+ *
+ * Map<String, String> parameter = new HashMap<String, String>();
+ *
+ * parameter.put(SessionParameter.ATOMPUB_URL, "http://localhost/cmis/atom");
+ * parameter.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value());
+ * parameter.put(SessionParameter.REPOSITORY_ID, "myRepository");
+ *
+ * parameter.put(SessionParameter.AUTHENTICATION_PROVIDER_CLASS, "org.apache.chemistry.opencmis.client.bindings.spi.OAuthAuthenticationProvider");
+ *
+ * parameter.put(SessionParameter.OAUTH_TOKEN_ENDPOINT, "https://example.com/auth/oauth/token");
+ * parameter.put(SessionParameter.OAUTH_CLIENT_ID, "s6BhdRkqt3");
+ * parameter.put(SessionParameter.OAUTH_CLIENT_SECRET, "7Fjfp0ZBr1KtDRbnfVdmIw");
+ *
+ * parameter.put(SessionParameter.OAUTH_ACCESS_TOKEN, "2YotnFZFEjr1zCsicMWpAA");
+ * parameter.put(SessionParameter.OAUTH_REFRESH_TOKEN, "tGzv3JOkF0XG5Qx2TlKWIA");
+ * parameter.put(SessionParameter.OAUTH_EXPIRATION_TIMESTAMP, "1388237075127");
+ *
+ * ...
+ * Session session = factory.createSession(parameter);
+ * </pre>
*/
public class OAuthAuthenticationProvider extends StandardAuthenticationProvider {
@@ -50,12 +106,58 @@ public class OAuthAuthenticationProvider
private static final long serialVersionUID = 1L;
- private String accessToken;
- private String refreshToken;
- private long expiresTimestamp;
-
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
+ private Token token = null;
+ private long defaultTokenLifetime = 3600;
+
+ @Override
+ public void setSession(BindingSession session) {
+ super.setSession(session);
+
+ if (token == null) {
+ // get predefined access token
+ String accessToken = null;
+ if (session.get(SessionParameter.OAUTH_ACCESS_TOKEN) instanceof String) {
+ accessToken = (String) session.get(SessionParameter.OAUTH_ACCESS_TOKEN);
+ }
+
+ // get predefined refresh token
+ String refreshToken = null;
+ if (session.get(SessionParameter.OAUTH_REFRESH_TOKEN) instanceof String) {
+ refreshToken = (String) session.get(SessionParameter.OAUTH_REFRESH_TOKEN);
+ }
+
+ // get predefined expiration timestamp
+ long expirationTimestamp = 0;
+ if (session.get(SessionParameter.OAUTH_EXPIRATION_TIMESTAMP) instanceof String) {
+ try {
+ expirationTimestamp = Long.parseLong((String) session
+ .get(SessionParameter.OAUTH_EXPIRATION_TIMESTAMP));
+ } catch (NumberFormatException nfe) {
+ // ignore
+ }
+ } else if (session.get(SessionParameter.OAUTH_EXPIRATION_TIMESTAMP) instanceof Number) {
+ expirationTimestamp = ((Number) session.get(SessionParameter.OAUTH_EXPIRATION_TIMESTAMP)).longValue();
+ }
+
+ // get default token lifetime
+ if (session.get(SessionParameter.OAUTH_DEFAULT_TOKEN_LIFETIME) instanceof String) {
+ try {
+ defaultTokenLifetime = Long.parseLong((String) session
+ .get(SessionParameter.OAUTH_DEFAULT_TOKEN_LIFETIME));
+ } catch (NumberFormatException nfe) {
+ // ignore
+ }
+ } else if (session.get(SessionParameter.OAUTH_DEFAULT_TOKEN_LIFETIME) instanceof Number) {
+ defaultTokenLifetime = ((Number) session.get(SessionParameter.OAUTH_DEFAULT_TOKEN_LIFETIME))
+ .longValue();
+ }
+
+ token = new Token(accessToken, refreshToken, expirationTimestamp);
+ }
+ }
+
@Override
public Map<String, List<String>> getHTTPHeaders(String url) {
Map<String, List<String>> headers = super.getHTTPHeaders(url);
@@ -63,26 +165,51 @@ public class OAuthAuthenticationProvider
headers = new HashMap<String, List<String>>();
}
- headers.put("Authorization", Collections.singletonList("Bearer " + getToken()));
+ headers.put("Authorization", Collections.singletonList("Bearer " + getAccessToken()));
return headers;
}
/**
+ * Returns the current token.
+ *
+ * @return the current token
+ */
+ public Token getToken() {
+ lock.readLock().lock();
+ try {
+ return token;
+ } finally {
+ lock.readLock().unlock();
+ }
+ }
+
+ @Override
+ protected boolean getSendBearerToken() {
+ // the super class should not handle bearer tokens
+ return false;
+ }
+
+ /**
* Gets the access token. If no access token is present or the access token
- * expired, a new token is requested.
+ * is expired, a new token is requested.
*
* @return the access token
*/
- protected String getToken() {
+ protected String getAccessToken() {
lock.writeLock().lock();
try {
- if (accessToken == null) {
- requestToken();
- } else if (System.currentTimeMillis() >= expiresTimestamp) {
+ if (token.getAccessToken() == null) {
+ if (token.getRefreshToken() == null) {
+ requestToken();
+ } else {
+ refreshToken();
+ }
+ } else if (token.isExpired()) {
refreshToken();
}
- return accessToken;
+
+ return token.getAccessToken();
} catch (CmisConnectionException ce) {
throw ce;
} catch (Exception e) {
@@ -94,25 +221,25 @@ public class OAuthAuthenticationProvider
private void requestToken() throws IOException {
if (LOG.isDebugEnabled()) {
- LOG.debug("Request new OAuth access token.");
+ LOG.debug("Requesting new OAuth access token.");
}
makeRequest(false);
- if (LOG.isDebugEnabled()) {
- LOG.debug("Access token: {} / Refresh token: {}", accessToken, refreshToken);
+ if (LOG.isTraceEnabled()) {
+ LOG.trace(token.toString());
}
}
private void refreshToken() throws IOException {
if (LOG.isDebugEnabled()) {
- LOG.debug("Refresh new OAuth access token.");
+ LOG.debug("Refreshing OAuth access token.");
}
makeRequest(true);
- if (LOG.isDebugEnabled()) {
- LOG.debug("Access token: {} / Refresh token: {}", accessToken, refreshToken);
+ if (LOG.isTraceEnabled()) {
+ LOG.trace(token.toString());
}
}
@@ -122,7 +249,7 @@ public class OAuthAuthenticationProvider
throw new CmisConnectionException("Token endpoint not set!");
}
- if (isRefresh && refreshToken == null) {
+ if (isRefresh && token.getRefreshToken() == null) {
throw new CmisConnectionException("No refresh token!");
}
@@ -143,7 +270,7 @@ public class OAuthAuthenticationProvider
writer.write("grant_type=refresh_token");
writer.write("&refresh_token=");
- writer.write(IOUtils.encodeURL(refreshToken));
+ writer.write(IOUtils.encodeURL(token.getRefreshToken()));
} else {
writer.write("grant_type=authorization_code");
@@ -201,16 +328,15 @@ public class OAuthAuthenticationProvider
Object jsonAccessToken = jsonResponse.get("access_token");
if (!(jsonAccessToken instanceof String)) {
- throw new CmisConnectionException("Invalid OAuth access token!");
+ throw new CmisConnectionException("Invalid OAuth access_token!");
}
Object jsonRefreshToken = jsonResponse.get("refresh_token");
if (jsonRefreshToken != null && !(jsonRefreshToken instanceof String)) {
- throw new CmisConnectionException("Invalid OAuth refresh token!");
+ throw new CmisConnectionException("Invalid OAuth refresh_token!");
}
- // default expiration time: 1 hour
- long expiresIn = 3600;
+ long expiresIn = defaultTokenLifetime;
Object jsonExpiresIn = jsonResponse.get("expires_in");
if (jsonExpiresIn != null) {
if (jsonExpiresIn instanceof Number) {
@@ -219,16 +345,15 @@ public class OAuthAuthenticationProvider
try {
expiresIn = Long.parseLong((String) jsonExpiresIn);
} catch (NumberFormatException nfe) {
- throw new CmisConnectionException("Invalid OAuth expires in value!");
+ throw new CmisConnectionException("Invalid OAuth expires_in value!");
}
} else {
- throw new CmisConnectionException("Invalid OAuth expires in value!");
+ throw new CmisConnectionException("Invalid OAuth expires_in value!");
}
}
- accessToken = jsonAccessToken.toString();
- refreshToken = (jsonRefreshToken == null ? null : jsonRefreshToken.toString());
- expiresTimestamp = expiresIn * 1000 + System.currentTimeMillis();
+ token = new Token(jsonAccessToken.toString(), (jsonRefreshToken == null ? null : jsonRefreshToken.toString()),
+ expiresIn * 1000 + System.currentTimeMillis());
}
private JSONObject parseResponse(HttpURLConnection conn) {
@@ -282,4 +407,63 @@ public class OAuthAuthenticationProvider
return charset;
}
+
+ /**
+ * Token holder class.
+ */
+ public static class Token {
+ private String accessToken;
+ private String refreshToken;
+ private long expirationTimestamp;
+
+ public Token(String accessToken, String refreshToken, long expirationTimestamp) {
+ this.accessToken = accessToken;
+ this.refreshToken = refreshToken;
+ this.expirationTimestamp = expirationTimestamp;
+ }
+
+ /**
+ * Returns the access token.
+ *
+ * @return the access token
+ */
+ public String getAccessToken() {
+ return accessToken;
+ }
+
+ /**
+ * Returns the refresh token.
+ *
+ * @return the refresh token
+ */
+ public String getRefreshToken() {
+ return refreshToken;
+ }
+
+ /**
+ * Returns the timestamp when the access expires.
+ *
+ * @return the timestamp in milliseconds since midnight, January 1, 1970
+ * UTC.
+ */
+ public long getExpirationTimestamp() {
+ return expirationTimestamp;
+ }
+
+ /**
+ * Returns whether the access token is expired or not.
+ *
+ * @return {@code true} if the access token is expired, {@code false}
+ * otherwise
+ */
+ public boolean isExpired() {
+ return System.currentTimeMillis() >= expirationTimestamp;
+ }
+
+ @Override
+ public String toString() {
+ return "Access token: " + accessToken + " / Refresh token: " + refreshToken + " / Expires : "
+ + expirationTimestamp;
+ }
+ }
}
Modified: chemistry/opencmis/trunk/chemistry-opencmis-commons/chemistry-opencmis-commons-api/src/main/java/org/apache/chemistry/opencmis/commons/SessionParameter.java
URL: http://svn.apache.org/viewvc/chemistry/opencmis/trunk/chemistry-opencmis-commons/chemistry-opencmis-commons-api/src/main/java/org/apache/chemistry/opencmis/commons/SessionParameter.java?rev=1553852&r1=1553851&r2=1553852&view=diff
==============================================================================
--- chemistry/opencmis/trunk/chemistry-opencmis-commons/chemistry-opencmis-commons-api/src/main/java/org/apache/chemistry/opencmis/commons/SessionParameter.java (original)
+++ chemistry/opencmis/trunk/chemistry-opencmis-commons/chemistry-opencmis-commons-api/src/main/java/org/apache/chemistry/opencmis/commons/SessionParameter.java Sat Dec 28 15:51:47 2013
@@ -583,7 +583,10 @@ public final class SessionParameter {
public static final String OAUTH_TOKEN_ENDPOINT = "org.apache.chemistry.opencmis.oauth.tokenEndpoint";
public static final String OAUTH_REDIRECT_URI = "org.apache.chemistry.opencmis.oauth.redirectUri";
- public static final String BREARER_ACCESS_TOKEN = "org.apache.chemistry.opencmis.oauth.accessToken";
+ public static final String OAUTH_ACCESS_TOKEN = "org.apache.chemistry.opencmis.oauth.accessToken";
+ public static final String OAUTH_REFRESH_TOKEN = "org.apache.chemistry.opencmis.oauth.refreshToken";
+ public static final String OAUTH_EXPIRATION_TIMESTAMP = "org.apache.chemistry.opencmis.oauth.expirationTimestamp";
+ public static final String OAUTH_DEFAULT_TOKEN_LIFETIME = "org.apache.chemistry.opencmis.oauth.defaultTokenLifetime";
// --- connection ---