You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@openwebbeans.apache.org by rm...@apache.org on 2017/01/13 18:33:52 UTC
svn commit: r1778650 - in /openwebbeans/meecrowave/trunk/meecrowave-oauth2:
./ src/main/java/org/apache/meecrowave/oauth2/configuration/
src/main/java/org/apache/meecrowave/oauth2/data/
src/main/java/org/apache/meecrowave/oauth2/resource/ src/test/java...
Author: rmannibucau
Date: Fri Jan 13 18:33:52 2017
New Revision: 1778650
URL: http://svn.apache.org/viewvc?rev=1778650&view=rev
Log:
adding authorization code endpoints (oauth2)
Added:
openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/main/java/org/apache/meecrowave/oauth2/resource/OAuth2AuthorizationCodeGrantService.java
openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/test/java/org/apache/meecrowave/oauth2/Keystores.java
Modified:
openwebbeans/meecrowave/trunk/meecrowave-oauth2/pom.xml
openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/main/java/org/apache/meecrowave/oauth2/configuration/OAuth2Configurer.java
openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/main/java/org/apache/meecrowave/oauth2/configuration/OAuth2Options.java
openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/main/java/org/apache/meecrowave/oauth2/data/RefreshTokenEnabledProvider.java
openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/main/java/org/apache/meecrowave/oauth2/resource/OAuth2Application.java
openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/test/java/org/apache/meecrowave/oauth2/OAuth2Test.java
Modified: openwebbeans/meecrowave/trunk/meecrowave-oauth2/pom.xml
URL: http://svn.apache.org/viewvc/openwebbeans/meecrowave/trunk/meecrowave-oauth2/pom.xml?rev=1778650&r1=1778649&r2=1778650&view=diff
==============================================================================
--- openwebbeans/meecrowave/trunk/meecrowave-oauth2/pom.xml (original)
+++ openwebbeans/meecrowave/trunk/meecrowave-oauth2/pom.xml Fri Jan 13 18:33:52 2017
@@ -99,12 +99,27 @@
<version>${project.version}</version>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.bouncycastle</groupId>
+ <artifactId>bcprov-jdk15</artifactId>
+ <version>1.46</version>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>3.5.1</version>
+ <configuration>
+ <fork>true</fork>
+ <compilerArgs>-XDignore.symbol.file</compilerArgs>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.3</version>
<executions>
Modified: openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/main/java/org/apache/meecrowave/oauth2/configuration/OAuth2Configurer.java
URL: http://svn.apache.org/viewvc/openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/main/java/org/apache/meecrowave/oauth2/configuration/OAuth2Configurer.java?rev=1778650&r1=1778649&r2=1778650&view=diff
==============================================================================
--- openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/main/java/org/apache/meecrowave/oauth2/configuration/OAuth2Configurer.java (original)
+++ openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/main/java/org/apache/meecrowave/oauth2/configuration/OAuth2Configurer.java Fri Jan 13 18:33:52 2017
@@ -21,6 +21,13 @@ package org.apache.meecrowave.oauth2.con
import org.apache.catalina.realm.GenericPrincipal;
import org.apache.cxf.Bus;
import org.apache.cxf.interceptor.security.AuthenticationException;
+import org.apache.cxf.jaxrs.ext.MessageContext;
+import org.apache.cxf.message.Message;
+import org.apache.cxf.phase.PhaseInterceptorChain;
+import org.apache.cxf.rs.security.jose.jwe.JweDecryptionProvider;
+import org.apache.cxf.rs.security.jose.jws.JwsSignatureVerifier;
+import org.apache.cxf.rs.security.jose.jws.JwsUtils;
+import org.apache.cxf.rs.security.oauth2.common.OAuthRedirectionState;
import org.apache.cxf.rs.security.oauth2.common.UserSubject;
import org.apache.cxf.rs.security.oauth2.grants.AbstractGrantHandler;
import org.apache.cxf.rs.security.oauth2.grants.clientcred.ClientCredentialsGrantHandler;
@@ -38,8 +45,10 @@ import org.apache.cxf.rs.security.oauth2
import org.apache.cxf.rs.security.oauth2.provider.DefaultEncryptingOAuthDataProvider;
import org.apache.cxf.rs.security.oauth2.provider.JCacheOAuthDataProvider;
import org.apache.cxf.rs.security.oauth2.provider.JPAOAuthDataProvider;
+import org.apache.cxf.rs.security.oauth2.provider.JoseSessionTokenProvider;
import org.apache.cxf.rs.security.oauth2.provider.OAuthDataProvider;
import org.apache.cxf.rs.security.oauth2.services.AbstractTokenService;
+import org.apache.cxf.rs.security.oauth2.services.RedirectionBasedGrantService;
import org.apache.cxf.rs.security.oauth2.utils.OAuthConstants;
import org.apache.meecrowave.Meecrowave;
import org.apache.meecrowave.oauth2.data.RefreshTokenEnabledProvider;
@@ -54,6 +63,8 @@ import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.StringReader;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.security.Principal;
import java.util.ArrayList;
@@ -65,12 +76,14 @@ import java.util.Properties;
import java.util.function.Consumer;
import static java.util.Arrays.asList;
+import static java.util.Collections.emptySet;
import static java.util.Locale.ENGLISH;
import static java.util.Optional.ofNullable;
+import static java.util.stream.Collectors.toMap;
import static org.apache.cxf.rs.security.oauth2.common.AuthenticationMethod.PASSWORD;
@ApplicationScoped
-public class OAuth2Configurer implements Consumer<AbstractTokenService> {
+public class OAuth2Configurer {
@Inject
private Meecrowave.Builder builder;
@@ -81,6 +94,7 @@ public class OAuth2Configurer implements
private HttpServletRequest request;
private Consumer<OAuth2TokenService> tokenServiceConsumer;
+ private Consumer<RedirectionBasedGrantService> redirectionBasedGrantServiceConsumer;
private Consumer<AbstractTokenService> abstractTokenServiceConsumer;
private OAuth2Options configuration;
@@ -91,10 +105,12 @@ public class OAuth2Configurer implements
AbstractOAuthDataProvider provider;
switch (configuration.getProvider().toLowerCase(ENGLISH)) {
case "jpa": {
- final JPAOAuthDataProvider jpaProvider = new JPAOAuthDataProvider();
- jpaProvider.setEntityManagerFactory(JPAAdapter.createEntityManagerFactory(configuration));
- provider = jpaProvider;
- break;
+ if (!configuration.isAuthorizationCodeSupport()) { // else use code impl
+ final JPAOAuthDataProvider jpaProvider = new JPAOAuthDataProvider();
+ jpaProvider.setEntityManagerFactory(JPAAdapter.createEntityManagerFactory(configuration));
+ provider = jpaProvider;
+ break;
+ }
}
case "jpa-code": {
final JPACodeDataProvider jpaProvider = new JPACodeDataProvider();
@@ -103,12 +119,14 @@ public class OAuth2Configurer implements
break;
}
case "jcache":
- try {
- provider = new JCacheOAuthDataProvider(configuration.getJcacheConfigUri(), bus, configuration.isJcacheStoreJwtKeyOnly());
- } catch (final Exception e) {
- throw new IllegalStateException(e);
+ if (!configuration.isAuthorizationCodeSupport()) { // else use code impl
+ try {
+ provider = new JCacheOAuthDataProvider(configuration.getJcacheConfigUri(), bus, configuration.isJcacheStoreJwtKeyOnly());
+ } catch (final Exception e) {
+ throw new IllegalStateException(e);
+ }
+ break;
}
- break;
case "jcache-code":
try {
provider = new JCacheCodeDataProvider(configuration.getJcacheConfigUri(), bus);
@@ -120,9 +138,11 @@ public class OAuth2Configurer implements
provider = new DefaultEHCacheOAuthDataProvider(configuration.getJcacheConfigUri(), bus);
break;
case "encrypted":
- provider = new DefaultEncryptingOAuthDataProvider(
- new SecretKeySpec(configuration.getEncryptedKey().getBytes(StandardCharsets.UTF_8), configuration.getEncryptedAlgo()));
- break;
+ if (!configuration.isAuthorizationCodeSupport()) { // else use code impl
+ provider = new DefaultEncryptingOAuthDataProvider(
+ new SecretKeySpec(configuration.getEncryptedKey().getBytes(StandardCharsets.UTF_8), configuration.getEncryptedAlgo()));
+ break;
+ }
case "encrypted-code":
provider = new DefaultEncryptingCodeDataProvider(
new SecretKeySpec(configuration.getEncryptedKey().getBytes(StandardCharsets.UTF_8), configuration.getEncryptedAlgo()));
@@ -136,31 +156,30 @@ public class OAuth2Configurer implements
refreshTokenGrantHandler.setUseAllClientScopes(configuration.isUseAllClientScopes());
refreshTokenGrantHandler.setPartialMatchScopeValidation(configuration.isPartialMatchScopeValidation());
+ final ResourceOwnerLoginHandler loginHandler = configuration.isJaas() ? new JAASResourceOwnerLoginHandler() : (name, password) -> {
+ try {
+ request.login(name, password);
+ try {
+ final Principal pcp = request.getUserPrincipal();
+ final UserSubject userSubject = new UserSubject(
+ name,
+ GenericPrincipal.class.isInstance(pcp) ?
+ new ArrayList<>(asList(GenericPrincipal.class.cast(pcp).getRoles())) : Collections.emptyList());
+ userSubject.setAuthenticationMethod(PASSWORD);
+ return userSubject;
+ } finally {
+ request.logout();
+ }
+ } catch (final ServletException e) {
+ throw new AuthenticationException(e.getMessage());
+ }
+ };
+
final List<AccessTokenGrantHandler> handlers = new ArrayList<>();
handlers.add(refreshTokenGrantHandler);
handlers.add(new ClientCredentialsGrantHandler());
handlers.add(new ResourceOwnerGrantHandler() {{
- setLoginHandler(configuration.isJaas() ? new JAASResourceOwnerLoginHandler() : new ResourceOwnerLoginHandler() {
- @Override
- public UserSubject createSubject(final String name, final String password) {
- try {
- request.login(name, password);
- try {
- final Principal pcp = request.getUserPrincipal();
- final UserSubject userSubject = new UserSubject(
- name,
- GenericPrincipal.class.isInstance(pcp) ?
- new ArrayList<>(asList(GenericPrincipal.class.cast(pcp).getRoles())) : Collections.emptyList());
- userSubject.setAuthenticationMethod(PASSWORD);
- return userSubject;
- } finally {
- request.logout();
- }
- } catch (final ServletException e) {
- throw new AuthenticationException(e.getMessage());
- }
- }
- });
+ setLoginHandler(loginHandler);
}});
handlers.add(new AuthorizationCodeGrantHandler());
handlers.add(new JwtBearerGrantHandler());
@@ -212,9 +231,75 @@ public class OAuth2Configurer implements
abstractTokenServiceConsumer.accept(s);
s.setGrantHandlers(handlers);
};
+
+ final List<String> noConsentScopes = ofNullable(configuration.getScopesRequiringNoConsent())
+ .map(s -> asList(s.split(",")))
+ .orElse(null);
+
+ // we prefix them oauth2.cxf. but otherwise it is the plain cxf config
+ final Map<String, String> contextualProperties = ofNullable(builder.getProperties()).map(Properties::stringPropertyNames).orElse(emptySet()).stream()
+ .filter(s -> s.startsWith("oauth2.cxf.rs.security."))
+ .collect(toMap(s -> s.substring("oauth2.cxf.".length()), s -> builder.getProperties().getProperty(s)));
+
+ final JoseSessionTokenProvider sessionAuthenticityTokenProvider = new JoseSessionTokenProvider() {
+ // getSessionState() is buggy in cxf 3.1.9 so we fix it there
+ private final Method convertStateStringToState;
+
+ {
+ try {
+ convertStateStringToState = JoseSessionTokenProvider.class.getDeclaredMethod("convertStateStringToState", String.class);
+ if (!convertStateStringToState.isAccessible()) {
+ convertStateStringToState.setAccessible(true);
+ }
+ } catch (final NoSuchMethodException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ @Override
+ public OAuthRedirectionState getSessionState(final MessageContext messageContext, final String sessionToken,
+ final UserSubject subject) {
+ final JweDecryptionProvider jwe = getInitializedDecryptionProvider();
+ final JwsSignatureVerifier jws = getInitializedSigVerifier();
+ String stateString = jwe.decrypt(sessionToken).getContentText();
+ if (jws != null) {
+ stateString = JwsUtils.verify(jws, stateString).getDecodedJwsPayload();
+ }
+ try {
+ return OAuthRedirectionState.class.cast(convertStateStringToState.invoke(this, stateString));
+ } catch (IllegalAccessException e) {
+ throw new IllegalStateException(e);
+ } catch (InvocationTargetException e) {
+ final Throwable cause = e.getCause();
+ if (RuntimeException.class.isInstance(cause)) {
+ throw RuntimeException.class.cast(cause);
+ }
+ throw new IllegalStateException(cause);
+ }
+
+ }
+ };
+ sessionAuthenticityTokenProvider.setMaxDefaultSessionInterval(configuration.getMaxDefaultSessionInterval());
+ // TODO: other configs
+
+ redirectionBasedGrantServiceConsumer = s -> {
+ s.setDataProvider(dataProvider);
+ s.setBlockUnsecureRequests(configuration.isBlockUnsecureRequests());
+ s.setWriteOptionalParameters(configuration.isWriteOptionalParameters());
+ s.setUseAllClientScopes(configuration.isUseAllClientScopes());
+ s.setPartialMatchScopeValidation(configuration.isPartialMatchScopeValidation());
+ s.setUseRegisteredRedirectUriIfPossible(configuration.isUseRegisteredRedirectUriIfPossible());
+ s.setMaxDefaultSessionInterval(configuration.getMaxDefaultSessionInterval());
+ s.setMatchRedirectUriWithApplicationUri(configuration.isMatchRedirectUriWithApplicationUri());
+ s.setScopesRequiringNoConsent(noConsentScopes);
+ s.setSessionAuthenticityTokenProvider(sessionAuthenticityTokenProvider);
+
+ // TODO: make it even more contextual, client based?
+ final Message currentMessage = PhaseInterceptorChain.getCurrentMessage();
+ contextualProperties.forEach(currentMessage::put);
+ };
}
- @Override
public void accept(final AbstractTokenService service) {
abstractTokenServiceConsumer.accept(service);
}
@@ -223,6 +308,10 @@ public class OAuth2Configurer implements
tokenServiceConsumer.accept(service);
}
+ public void accept(final RedirectionBasedGrantService service) {
+ redirectionBasedGrantServiceConsumer.accept(service);
+ }
+
public OAuth2Options getConfiguration() {
return configuration;
}
Modified: openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/main/java/org/apache/meecrowave/oauth2/configuration/OAuth2Options.java
URL: http://svn.apache.org/viewvc/openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/main/java/org/apache/meecrowave/oauth2/configuration/OAuth2Options.java?rev=1778650&r1=1778649&r2=1778650&view=diff
==============================================================================
--- openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/main/java/org/apache/meecrowave/oauth2/configuration/OAuth2Options.java (original)
+++ openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/main/java/org/apache/meecrowave/oauth2/configuration/OAuth2Options.java Fri Jan 13 18:33:52 2017
@@ -127,6 +127,33 @@ public class OAuth2Options implements Cl
@CliOption(name = "oauth2-encrypted-algorithm", description = "The algorithm for the key for the encrypted provider")
private String encryptedAlgo;
+ @CliOption(name = "oauth2-token-support", description = "Are token flows supported")
+ private boolean tokenSupport = true;
+
+ @CliOption(name = "oauth2-authorization-code-support", description = "Is authorization code flow supported")
+ private boolean authorizationCodeSupport;
+
+ @CliOption(name = "oauth2-redirection-use-registered-redirect-uri-if-possible", description = "For authorization code flow, should the registered uri be used")
+ private boolean useRegisteredRedirectUriIfPossible = true;
+
+ /*
+ private SessionAuthenticityTokenProvider sessionAuthenticityTokenProvider;
+ private SubjectCreator subjectCreator;
+ private ResourceOwnerNameProvider resourceOwnerNameProvider;
+ private AuthorizationRequestFilter authorizationFilter;
+ */
+
+ @CliOption(name = "oauth2-redirection-max-default-session-interval", description = "For authorization code flow, how long a session can be")
+ private int maxDefaultSessionInterval;
+
+ @CliOption(
+ name = "oauth2-redirection-match-redirect-uri-with-application-uri",
+ description = "For authorization code flow, should redirect uri be matched with application one")
+ private boolean matchRedirectUriWithApplicationUri;
+
+ @CliOption(name = "oauth2-redirection-scopes-requiring-no-consent", description = "For authorization code flow, the scopes using no consent")
+ private String scopesRequiringNoConsent;
+
public String getEncryptedAlgo() {
return encryptedAlgo;
}
@@ -406,4 +433,52 @@ public class OAuth2Options implements Cl
public void setUseAllClientScopes(final boolean useAllClientScopes) {
this.useAllClientScopes = useAllClientScopes;
}
+
+ public boolean isAuthorizationCodeSupport() {
+ return authorizationCodeSupport;
+ }
+
+ public void setAuthorizationCodeSupport(final boolean authorizationCodeSupport) {
+ this.authorizationCodeSupport = authorizationCodeSupport;
+ }
+
+ public boolean isUseRegisteredRedirectUriIfPossible() {
+ return useRegisteredRedirectUriIfPossible;
+ }
+
+ public void setUseRegisteredRedirectUriIfPossible(final boolean useRegisteredRedirectUriIfPossible) {
+ this.useRegisteredRedirectUriIfPossible = useRegisteredRedirectUriIfPossible;
+ }
+
+ public int getMaxDefaultSessionInterval() {
+ return maxDefaultSessionInterval;
+ }
+
+ public void setMaxDefaultSessionInterval(final int maxDefaultSessionInterval) {
+ this.maxDefaultSessionInterval = maxDefaultSessionInterval;
+ }
+
+ public boolean isMatchRedirectUriWithApplicationUri() {
+ return matchRedirectUriWithApplicationUri;
+ }
+
+ public void setMatchRedirectUriWithApplicationUri(final boolean matchRedirectUriWithApplicationUri) {
+ this.matchRedirectUriWithApplicationUri = matchRedirectUriWithApplicationUri;
+ }
+
+ public String getScopesRequiringNoConsent() {
+ return scopesRequiringNoConsent;
+ }
+
+ public void setScopesRequiringNoConsent(final String scopesRequiringNoConsent) {
+ this.scopesRequiringNoConsent = scopesRequiringNoConsent;
+ }
+
+ public boolean isTokenSupport() {
+ return tokenSupport;
+ }
+
+ public void setTokenSupport(final boolean tokenSupport) {
+ this.tokenSupport = tokenSupport;
+ }
}
Modified: openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/main/java/org/apache/meecrowave/oauth2/data/RefreshTokenEnabledProvider.java
URL: http://svn.apache.org/viewvc/openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/main/java/org/apache/meecrowave/oauth2/data/RefreshTokenEnabledProvider.java?rev=1778650&r1=1778649&r2=1778650&view=diff
==============================================================================
--- openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/main/java/org/apache/meecrowave/oauth2/data/RefreshTokenEnabledProvider.java (original)
+++ openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/main/java/org/apache/meecrowave/oauth2/data/RefreshTokenEnabledProvider.java Fri Jan 13 18:33:52 2017
@@ -23,6 +23,9 @@ import org.apache.cxf.rs.security.oauth2
import org.apache.cxf.rs.security.oauth2.common.OAuthPermission;
import org.apache.cxf.rs.security.oauth2.common.ServerAccessToken;
import org.apache.cxf.rs.security.oauth2.common.UserSubject;
+import org.apache.cxf.rs.security.oauth2.grants.code.AuthorizationCodeDataProvider;
+import org.apache.cxf.rs.security.oauth2.grants.code.AuthorizationCodeRegistration;
+import org.apache.cxf.rs.security.oauth2.grants.code.ServerAuthorizationCodeGrant;
import org.apache.cxf.rs.security.oauth2.provider.AbstractOAuthDataProvider;
import org.apache.cxf.rs.security.oauth2.provider.OAuthDataProvider;
import org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException;
@@ -34,7 +37,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
-public class RefreshTokenEnabledProvider implements OAuthDataProvider {
+public class RefreshTokenEnabledProvider implements OAuthDataProvider, AuthorizationCodeDataProvider {
private final OAuthDataProvider delegate;
public RefreshTokenEnabledProvider(final OAuthDataProvider delegate) {
@@ -106,4 +109,30 @@ public class RefreshTokenEnabledProvider
public List<OAuthPermission> convertScopeToPermissions(final Client client, final List<String> requestedScopes) {
return delegate.convertScopeToPermissions(client, requestedScopes);
}
+
+ public OAuthDataProvider getDelegate() {
+ return delegate;
+ }
+
+ private AuthorizationCodeDataProvider getCodeDelegate() {
+ if (!AuthorizationCodeDataProvider.class.isInstance(delegate)) {
+ throw new UnsupportedOperationException("Not a AuthorizationCodeDataProvider");
+ }
+ return AuthorizationCodeDataProvider.class.cast(delegate);
+ }
+
+ @Override
+ public ServerAuthorizationCodeGrant createCodeGrant(final AuthorizationCodeRegistration reg) throws OAuthServiceException {
+ return getCodeDelegate().createCodeGrant(reg);
+ }
+
+ @Override
+ public ServerAuthorizationCodeGrant removeCodeGrant(final String code) throws OAuthServiceException {
+ return getCodeDelegate().removeCodeGrant(code);
+ }
+
+ @Override
+ public List<ServerAuthorizationCodeGrant> getCodeGrants(final Client c, final UserSubject subject) throws OAuthServiceException {
+ return getCodeDelegate().getCodeGrants(c, subject);
+ }
}
Modified: openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/main/java/org/apache/meecrowave/oauth2/resource/OAuth2Application.java
URL: http://svn.apache.org/viewvc/openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/main/java/org/apache/meecrowave/oauth2/resource/OAuth2Application.java?rev=1778650&r1=1778649&r2=1778650&view=diff
==============================================================================
--- openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/main/java/org/apache/meecrowave/oauth2/resource/OAuth2Application.java (original)
+++ openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/main/java/org/apache/meecrowave/oauth2/resource/OAuth2Application.java Fri Jan 13 18:33:52 2017
@@ -20,24 +20,41 @@ package org.apache.meecrowave.oauth2.res
import org.apache.cxf.rs.security.oauth2.common.Client;
import org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider;
+import org.apache.meecrowave.Meecrowave;
+import org.apache.meecrowave.oauth2.configuration.OAuth2Options;
import javax.enterprise.context.Dependent;
+import javax.inject.Inject;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import java.util.HashSet;
import java.util.Set;
import static java.util.Arrays.asList;
+import static java.util.Collections.singletonList;
@Dependent
@ApplicationPath("oauth2")
public class OAuth2Application extends Application {
+ @Inject
+ private Meecrowave.Builder builder;
+
private Set<Class<?>> classes;
@Override
public Set<Class<?>> getClasses() {
- return classes != null ? classes : (classes = new HashSet<>(asList(
- OAuth2TokenService.class, OAuthJSONProvider.class)));
+ return classes != null ? classes : (classes = doGetClasses());
+ }
+
+ private Set<Class<?>> doGetClasses() {
+ final Set<Class<?>> classes = new HashSet<>(singletonList(OAuthJSONProvider.class));
+ if (builder.getExtension(OAuth2Options.class).isAuthorizationCodeSupport()) {
+ classes.add(OAuth2AuthorizationCodeGrantService.class);
+ }
+ if (builder.getExtension(OAuth2Options.class).isTokenSupport()) {
+ classes.addAll(asList(OAuth2TokenService.class, OAuth2RevokeTokenService.class));
+ }
+ return classes;
}
interface Defaults {
Added: openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/main/java/org/apache/meecrowave/oauth2/resource/OAuth2AuthorizationCodeGrantService.java
URL: http://svn.apache.org/viewvc/openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/main/java/org/apache/meecrowave/oauth2/resource/OAuth2AuthorizationCodeGrantService.java?rev=1778650&view=auto
==============================================================================
--- openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/main/java/org/apache/meecrowave/oauth2/resource/OAuth2AuthorizationCodeGrantService.java (added)
+++ openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/main/java/org/apache/meecrowave/oauth2/resource/OAuth2AuthorizationCodeGrantService.java Fri Jan 13 18:33:52 2017
@@ -0,0 +1,39 @@
+/*
+ * 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.meecrowave.oauth2.resource;
+
+import org.apache.cxf.rs.security.oauth2.services.AuthorizationCodeGrantService;
+import org.apache.meecrowave.oauth2.configuration.OAuth2Configurer;
+
+import javax.annotation.PostConstruct;
+import javax.enterprise.context.RequestScoped;
+import javax.inject.Inject;
+import javax.ws.rs.Path;
+
+@RequestScoped
+@Path("authorize")
+public class OAuth2AuthorizationCodeGrantService extends AuthorizationCodeGrantService {
+ @Inject
+ private OAuth2Configurer configurer;
+
+ @PostConstruct
+ private void init() {
+ configurer.accept(this);
+ }
+}
Added: openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/test/java/org/apache/meecrowave/oauth2/Keystores.java
URL: http://svn.apache.org/viewvc/openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/test/java/org/apache/meecrowave/oauth2/Keystores.java?rev=1778650&view=auto
==============================================================================
--- openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/test/java/org/apache/meecrowave/oauth2/Keystores.java (added)
+++ openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/test/java/org/apache/meecrowave/oauth2/Keystores.java Fri Jan 13 18:33:52 2017
@@ -0,0 +1,108 @@
+/*
+ * 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.meecrowave.oauth2;
+
+import org.apache.cxf.rt.security.crypto.CryptoUtils;
+import sun.security.tools.keytool.CertAndKeyGen;
+import sun.security.x509.BasicConstraintsExtension;
+import sun.security.x509.CertificateExtensions;
+import sun.security.x509.X500Name;
+import sun.security.x509.X509CertImpl;
+import sun.security.x509.X509CertInfo;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.OutputStream;
+import java.security.KeyStore;
+import java.security.Principal;
+import java.security.PrivateKey;
+import java.security.cert.X509Certificate;
+
+public final class Keystores {
+ private Keystores() {
+ // no-op
+ }
+
+ public static void create(final File keystore) throws Exception {
+ CryptoUtils.installBouncyCastleProvider();
+
+ final KeyStore ks = KeyStore.getInstance("JKS");
+ ks.load(null, "password".toCharArray());
+
+ final CertAndKeyGen keyGen = new CertAndKeyGen("RSA", "SHA1WithRSA", null);
+ keyGen.generate(2048);
+ PrivateKey rootPrivateKey = keyGen.getPrivateKey();
+
+ X509Certificate rootCertificate = keyGen.getSelfCertificate(new X500Name("cn=root"), (long) 365 * 24 * 60 * 60);
+
+ final CertAndKeyGen keyGen1 = new CertAndKeyGen("RSA", "SHA1WithRSA", null);
+ keyGen1.generate(2048);
+ final PrivateKey middlePrivateKey = keyGen1.getPrivateKey();
+
+ X509Certificate middleCertificate = keyGen1.getSelfCertificate(new X500Name("CN=MIDDLE"), (long) 365 * 24 * 60 * 60);
+
+ //Generate leaf certificate
+ final CertAndKeyGen keyGen2 = new CertAndKeyGen("RSA", "SHA1WithRSA", null);
+ keyGen2.generate(2048);
+ final PrivateKey topPrivateKey = keyGen2.getPrivateKey();
+
+ X509Certificate topCertificate = keyGen2.getSelfCertificate(new X500Name("cn=root"), (long) 365 * 24 * 60 * 60);
+
+ rootCertificate = createSignedCertificate(rootCertificate, rootCertificate, rootPrivateKey);
+ middleCertificate = createSignedCertificate(middleCertificate, rootCertificate, rootPrivateKey);
+ topCertificate = createSignedCertificate(topCertificate, middleCertificate, middlePrivateKey);
+
+ final X509Certificate[] chain = new X509Certificate[]{topCertificate, middleCertificate, rootCertificate};
+
+ ks.setKeyEntry("alice", topPrivateKey, "pwd".toCharArray(), chain);
+
+
+ keystore.getParentFile().mkdirs();
+ try (final OutputStream os = new FileOutputStream(keystore)) {
+ ks.store(os, "password".toCharArray());
+ }
+ }
+
+ private static X509Certificate createSignedCertificate(final X509Certificate cetrificate, final X509Certificate issuerCertificate,
+ final PrivateKey issuerPrivateKey) {
+ try {
+ Principal issuer = issuerCertificate.getSubjectDN();
+ String issuerSigAlg = issuerCertificate.getSigAlgName();
+
+ byte[] inCertBytes = cetrificate.getTBSCertificate();
+ X509CertInfo info = new X509CertInfo(inCertBytes);
+ info.set(X509CertInfo.ISSUER, (X500Name) issuer);
+
+ //No need to add the BasicContraint for leaf cert
+ if (!cetrificate.getSubjectDN().getName().equals("CN=TOP")) {
+ CertificateExtensions exts = new CertificateExtensions();
+ BasicConstraintsExtension bce = new BasicConstraintsExtension(true, -1);
+ exts.set(BasicConstraintsExtension.NAME, new BasicConstraintsExtension(false, bce.getExtensionValue()));
+ info.set(X509CertInfo.EXTENSIONS, exts);
+ }
+
+ final X509CertImpl outCert = new X509CertImpl(info);
+ outCert.sign(issuerPrivateKey, issuerSigAlg);
+
+ return outCert;
+ } catch (final Exception ex) {
+ throw new IllegalStateException(ex);
+ }
+ }
+}
Modified: openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/test/java/org/apache/meecrowave/oauth2/OAuth2Test.java
URL: http://svn.apache.org/viewvc/openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/test/java/org/apache/meecrowave/oauth2/OAuth2Test.java?rev=1778650&r1=1778649&r2=1778650&view=diff
==============================================================================
--- openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/test/java/org/apache/meecrowave/oauth2/OAuth2Test.java (original)
+++ openwebbeans/meecrowave/trunk/meecrowave-oauth2/src/test/java/org/apache/meecrowave/oauth2/OAuth2Test.java Fri Jan 13 18:33:52 2017
@@ -18,28 +18,70 @@
*/
package org.apache.meecrowave.oauth2;
+import org.apache.cxf.common.classloader.ClassLoaderUtils;
+import org.apache.cxf.message.Message;
import org.apache.cxf.rs.security.oauth2.common.ClientAccessToken;
+import org.apache.cxf.rs.security.oauth2.common.OAuthAuthorizationData;
import org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider;
+import org.apache.cxf.rs.security.oauth2.utils.OAuthConstants;
import org.apache.meecrowave.Meecrowave;
import org.apache.meecrowave.junit.MeecrowaveRule;
+import org.apache.meecrowave.oauth2.provider.JCacheCodeDataProvider;
+import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
+import javax.cache.Cache;
+import javax.cache.CacheManager;
+import javax.cache.Caching;
+import javax.cache.configuration.MutableConfiguration;
+import javax.cache.spi.CachingProvider;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
+import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Form;
+import javax.ws.rs.core.Response;
+import java.io.File;
+import java.net.URISyntaxException;
+import java.nio.charset.StandardCharsets;
+import static java.util.Collections.singletonList;
import static javax.ws.rs.client.Entity.entity;
import static javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED_TYPE;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE;
+import static javax.xml.bind.DatatypeConverter.printBase64Binary;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
public class OAuth2Test {
+ private static final File KEYSTORE = new File("target/OAuth2Test/keystore.jceks");
+
@ClassRule
public static final MeecrowaveRule MEECROWAVE = new MeecrowaveRule(
- new Meecrowave.Builder().randomHttpPort().user("test", "pwd").role("test", "admin"), "");
+ new Meecrowave.Builder().randomHttpPort()
+ .user("test", "pwd").role("test", "admin")
+ // auth code support is optional so activate it
+ .property("oauth2-authorization-code-support", "true")
+ // auth code jose setup to store the tokens
+ .property("oauth2.cxf.rs.security.keystore.type", "jks")
+ .property("oauth2.cxf.rs.security.keystore.file", KEYSTORE.getAbsolutePath())
+ .property("oauth2.cxf.rs.security.keystore.password", "password")
+ .property("oauth2.cxf.rs.security.keystore.alias", "alice")
+ .property("oauth2.cxf.rs.security.key.password", "pwd")
+ // auth code needs a logged pcp to work
+ .loginConfig(new Meecrowave.LoginConfigBuilder().basic())
+ .securityConstraints(new Meecrowave.SecurityConstaintBuilder()
+ .authConstraint(true)
+ .addAuthRole("**")
+ .addCollection("secured", "/oauth2/authorize")
+ .addCollection("secured", "/oauth2/authorize/decision")), "");
+
+ @BeforeClass
+ public static void createKeyStore() throws Exception {
+ Keystores.create(KEYSTORE);
+ }
@Test
public void getPasswordTokenNoClient() {
@@ -96,4 +138,67 @@ public class OAuth2Test {
client.close();
}
}
+
+ @Test
+ public void authorizationCode() throws URISyntaxException {
+ final int httpPort = MEECROWAVE.getConfiguration().getHttpPort();
+
+ createRedirectedClient(httpPort);
+
+ final Client client = ClientBuilder.newClient()
+ .property(Message.MAINTAIN_SESSION, true)
+ .register(new OAuthJSONProvider());
+ try {
+ final WebTarget target = client.target("http://localhost:" + httpPort);
+
+ final Response authorization = target
+ .path("oauth2/authorize")
+ .queryParam(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE_GRANT)
+ .queryParam(OAuthConstants.RESPONSE_TYPE, OAuthConstants.CODE_RESPONSE_TYPE)
+ .queryParam(OAuthConstants.CLIENT_ID, "c1")
+ .queryParam(OAuthConstants.CLIENT_SECRET, "cpwd")
+ .queryParam("redirect_uri", "http://localhost:" + httpPort + "/redirected")
+ .request(APPLICATION_JSON_TYPE)
+ .header("authorization", "Basic " + printBase64Binary("test:pwd".getBytes(StandardCharsets.UTF_8)))
+ .get();
+ final OAuthAuthorizationData data = authorization.readEntity(OAuthAuthorizationData.class);
+ assertNotNull(data.getAuthenticityToken());
+ assertEquals("c1", data.getClientId());
+ assertEquals("http://localhost:" + httpPort + "/oauth2/authorize/decision", data.getReplyTo());
+ assertEquals("code", data.getResponseType());
+ assertEquals("http://localhost:" + httpPort + "/redirected", data.getRedirectUri());
+
+ final Response decision = target
+ .path("oauth2/authorize/decision")
+ .queryParam(OAuthConstants.SESSION_AUTHENTICITY_TOKEN, data.getAuthenticityToken())
+ .queryParam(OAuthConstants.AUTHORIZATION_DECISION_KEY, "allow")
+ .request(APPLICATION_JSON_TYPE)
+ .cookie(authorization.getCookies().get("JSESSIONID"))
+ .header("authorization", "Basic " + printBase64Binary("test:pwd".getBytes(StandardCharsets.UTF_8)))
+ .get();
+ assertEquals(Response.Status.SEE_OTHER.getStatusCode(), decision.getStatus());
+ assertTrue(decision.getLocation().toASCIIString(), decision.getLocation().toASCIIString().startsWith("http://localhost:" + httpPort + "/redirected?code="));
+ } finally {
+ client.close();
+ }
+ }
+
+ private void createRedirectedClient(final int httpPort) throws URISyntaxException {
+ final CachingProvider provider = Caching.getCachingProvider();
+ final CacheManager cacheManager = provider.getCacheManager(
+ ClassLoaderUtils.getResource("default-oauth2.jcs", OAuth2Test.class).toURI(),
+ provider.getDefaultClassLoader());
+ Cache<String, org.apache.cxf.rs.security.oauth2.common.Client> cache;
+ try {
+ cache = cacheManager
+ .createCache(JCacheCodeDataProvider.CLIENT_CACHE_KEY, new MutableConfiguration<String, org.apache.cxf.rs.security.oauth2.common.Client>()
+ .setTypes(String.class, org.apache.cxf.rs.security.oauth2.common.Client.class)
+ .setStoreByValue(true));
+ } catch (final RuntimeException re) {
+ cache = cacheManager.getCache(JCacheCodeDataProvider.CLIENT_CACHE_KEY, String.class, org.apache.cxf.rs.security.oauth2.common.Client.class);
+ }
+ final org.apache.cxf.rs.security.oauth2.common.Client value = new org.apache.cxf.rs.security.oauth2.common.Client("c1", "cpwd", true);
+ value.setRedirectUris(singletonList("http://localhost:" + httpPort + "/redirected"));
+ cache.put("c1", value);
+ }
}