You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cxf.apache.org by co...@apache.org on 2016/01/20 16:02:16 UTC
[1/5] cxf git commit: Reshuffle of the tests to share some common code
Repository: cxf
Updated Branches:
refs/heads/master 343d06d94 -> 2e8219cf3
http://git-wip-us.apache.org/repos/asf/cxf/blob/2e8219cf/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/JAXRSOAuth2Test.java
----------------------------------------------------------------------
diff --git a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/JAXRSOAuth2Test.java b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/JAXRSOAuth2Test.java
new file mode 100644
index 0000000..d21dc9b
--- /dev/null
+++ b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/JAXRSOAuth2Test.java
@@ -0,0 +1,508 @@
+/**
+ * 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.cxf.systest.jaxrs.security.oauth2.grants;
+
+import java.net.URL;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+import org.apache.cxf.Bus;
+import org.apache.cxf.bus.spring.SpringBusFactory;
+import org.apache.cxf.common.util.Base64UrlUtility;
+import org.apache.cxf.helpers.DOMUtils;
+import org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean;
+import org.apache.cxf.jaxrs.client.WebClient;
+import org.apache.cxf.jaxrs.impl.MetadataMap;
+import org.apache.cxf.rs.security.common.CryptoLoader;
+import org.apache.cxf.rs.security.oauth2.auth.saml.Saml2BearerAuthOutInterceptor;
+import org.apache.cxf.rs.security.oauth2.client.Consumer;
+import org.apache.cxf.rs.security.oauth2.client.OAuthClientUtils;
+import org.apache.cxf.rs.security.oauth2.common.AccessTokenGrant;
+import org.apache.cxf.rs.security.oauth2.common.ClientAccessToken;
+import org.apache.cxf.rs.security.oauth2.grants.jwt.JwtBearerGrant;
+import org.apache.cxf.rs.security.oauth2.grants.saml.Saml2BearerGrant;
+import org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException;
+import org.apache.cxf.rs.security.oauth2.saml.Constants;
+import org.apache.cxf.rs.security.oauth2.utils.OAuthConstants;
+import org.apache.cxf.rs.security.saml.SAMLUtils;
+import org.apache.cxf.rs.security.saml.SAMLUtils.SelfSignInfo;
+import org.apache.cxf.systest.jaxrs.security.oauth2.common.OAuth2TestUtils;
+import org.apache.cxf.systest.jaxrs.security.oauth2.common.SamlCallbackHandler;
+import org.apache.cxf.testutil.common.AbstractBusClientServerTestBase;
+import org.apache.wss4j.common.crypto.Crypto;
+import org.apache.wss4j.common.saml.SAMLCallback;
+import org.apache.wss4j.common.saml.SAMLUtil;
+import org.apache.wss4j.common.saml.SamlAssertionWrapper;
+import org.apache.wss4j.common.saml.builder.SAML2Constants;
+import org.apache.wss4j.common.util.DOM2Writer;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+public class JAXRSOAuth2Test extends AbstractBusClientServerTestBase {
+ public static final String PORT = BookServerOAuth2.PORT;
+ private static final String CRYPTO_RESOURCE_PROPERTIES =
+ "org/apache/cxf/systest/jaxrs/security/alice.properties";
+
+ @BeforeClass
+ public static void startServers() throws Exception {
+ assertTrue("server did not launch correctly",
+ launchServer(BookServerOAuth2.class, true));
+ }
+
+ @Test
+ public void testSAML2BearerGrant() throws Exception {
+ String address = "https://localhost:" + PORT + "/oauth2/token";
+ WebClient wc = createWebClient(address);
+
+ Crypto crypto = new CryptoLoader().loadCrypto(CRYPTO_RESOURCE_PROPERTIES);
+ SelfSignInfo signInfo = new SelfSignInfo(crypto, "alice", "password");
+
+ SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(false);
+ String audienceURI = "https://localhost:" + PORT + "/oauth2/token";
+ samlCallbackHandler.setAudience(audienceURI);
+ SamlAssertionWrapper assertionWrapper = SAMLUtils.createAssertion(samlCallbackHandler,
+ signInfo);
+ Document doc = DOMUtils.newDocument();
+ Element assertionElement = assertionWrapper.toDOM(doc);
+ String assertion = DOM2Writer.nodeToString(assertionElement);
+
+ Saml2BearerGrant grant = new Saml2BearerGrant(assertion);
+ ClientAccessToken at = OAuthClientUtils.getAccessToken(wc,
+ new Consumer("alice", "alice"),
+ grant,
+ false);
+ assertNotNull(at.getTokenKey());
+ }
+
+ @Test
+ public void testSAML2BearerAuthenticationDirect() throws Exception {
+ String address = "https://localhost:" + PORT + "/oauth2-auth/token";
+ WebClient wc = createWebClient(address);
+
+ Crypto crypto = new CryptoLoader().loadCrypto(CRYPTO_RESOURCE_PROPERTIES);
+ SelfSignInfo signInfo = new SelfSignInfo(crypto, "alice", "password");
+
+ SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(true);
+ samlCallbackHandler.setIssuer("alice");
+ String audienceURI = "https://localhost:" + PORT + "/oauth2-auth/token";
+ samlCallbackHandler.setAudience(audienceURI);
+ SamlAssertionWrapper assertionWrapper = SAMLUtils.createAssertion(samlCallbackHandler,
+ signInfo);
+ Document doc = DOMUtils.newDocument();
+ Element assertionElement = assertionWrapper.toDOM(doc);
+ String assertion = DOM2Writer.nodeToString(assertionElement);
+
+ String encodedAssertion = Base64UrlUtility.encode(assertion);
+
+ Map<String, String> extraParams = new HashMap<String, String>();
+ extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE, Constants.CLIENT_AUTH_SAML2_BEARER);
+ extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, encodedAssertion);
+
+ ClientAccessToken at = OAuthClientUtils.getAccessToken(wc,
+ new CustomGrant(),
+ extraParams);
+ assertNotNull(at.getTokenKey());
+ }
+
+ @Test
+ public void testTwoWayTLSAuthentication() throws Exception {
+ String address = "https://localhost:" + PORT + "/oauth2/token";
+ WebClient wc = createWebClient(address);
+
+ ClientAccessToken at = OAuthClientUtils.getAccessToken(wc, new CustomGrant());
+ assertNotNull(at.getTokenKey());
+ }
+
+ @Test
+ public void testSAML2BearerAuthenticationInterceptor() throws Exception {
+ String address = "https://localhost:" + PORT + "/oauth2-auth/token";
+ WebClient wc = createWebClientWithProps(address);
+
+ ClientAccessToken at = OAuthClientUtils.getAccessToken(wc,
+ new CustomGrant());
+ assertNotNull(at.getTokenKey());
+ }
+
+ @Test
+ public void testJWTBearerGrant() throws Exception {
+ String address = "https://localhost:" + PORT + "/oauth2/token";
+ WebClient wc = createWebClient(address);
+
+ // Create the JWT Token
+ String token = OAuth2TestUtils.createToken("resourceOwner", "alice", address, true, true);
+
+ JwtBearerGrant grant = new JwtBearerGrant(token);
+ ClientAccessToken at = OAuthClientUtils.getAccessToken(wc,
+ new Consumer("alice", "alice"),
+ grant,
+ false);
+ assertNotNull(at.getTokenKey());
+ }
+
+ @Test
+ public void testJWTBearerAuthenticationDirect() throws Exception {
+ String address = "https://localhost:" + PORT + "/oauth2-auth-jwt/token";
+ WebClient wc = createWebClient(address);
+
+ // Create the JWT Token
+ String token = OAuth2TestUtils.createToken("resourceOwner", "alice", address, true, true);
+
+ Map<String, String> extraParams = new HashMap<String, String>();
+ extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE,
+ "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
+ extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, token);
+
+ ClientAccessToken at = OAuthClientUtils.getAccessToken(wc,
+ new CustomGrant(),
+ extraParams);
+ assertNotNull(at.getTokenKey());
+ }
+
+ //
+ // Some negative tests for authentication
+ //
+
+ @Test
+ public void testSAML11() throws Exception {
+ String address = "https://localhost:" + PORT + "/oauth2-auth/token";
+ WebClient wc = createWebClient(address);
+
+ String audienceURI = "https://localhost:" + PORT + "/oauth2-auth/token";
+ String assertion = OAuth2TestUtils.createToken(audienceURI, false, true);
+ String encodedAssertion = Base64UrlUtility.encode(assertion);
+
+ Map<String, String> extraParams = new HashMap<String, String>();
+ extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE, Constants.CLIENT_AUTH_SAML2_BEARER);
+ extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, encodedAssertion);
+
+ try {
+ OAuthClientUtils.getAccessToken(wc, new CustomGrant(), extraParams);
+ fail("Failure expected on a SAML 1.1 Assertion");
+ } catch (OAuthServiceException ex) {
+ // expected
+ }
+ }
+
+ @Test
+ public void testSAMLAudRestr() throws Exception {
+ String address = "https://localhost:" + PORT + "/oauth2-auth/token";
+ WebClient wc = createWebClient(address);
+
+ String audienceURI = "https://localhost:" + PORT + "/oauth2-auth/token2";
+ String assertion = OAuth2TestUtils.createToken(audienceURI, true, true);
+ String encodedAssertion = Base64UrlUtility.encode(assertion);
+
+ Map<String, String> extraParams = new HashMap<String, String>();
+ extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE, Constants.CLIENT_AUTH_SAML2_BEARER);
+ extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, encodedAssertion);
+
+ try {
+ OAuthClientUtils.getAccessToken(wc, new CustomGrant(), extraParams);
+ fail("Failure expected on a bad audience restriction");
+ } catch (OAuthServiceException ex) {
+ // expected
+ }
+ }
+
+ @Test
+ public void testSAMLBadSubjectName() throws Exception {
+ String address = "https://localhost:" + PORT + "/oauth2-auth/token";
+ WebClient wc = createWebClient(address);
+
+ String audienceURI = "https://localhost:" + PORT + "/oauth2-auth/token";
+
+ // Create the SAML Assertion
+ SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(true);
+ samlCallbackHandler.setSubjectName("bob");
+ samlCallbackHandler.setAudience(audienceURI);
+
+ SAMLCallback samlCallback = new SAMLCallback();
+ SAMLUtil.doSAMLCallback(samlCallbackHandler, samlCallback);
+
+ SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback);
+ if (samlCallback.isSignAssertion()) {
+ samlAssertion.signAssertion(
+ samlCallback.getIssuerKeyName(),
+ samlCallback.getIssuerKeyPassword(),
+ samlCallback.getIssuerCrypto(),
+ samlCallback.isSendKeyValue(),
+ samlCallback.getCanonicalizationAlgorithm(),
+ samlCallback.getSignatureAlgorithm()
+ );
+ }
+
+ String assertion = samlAssertion.assertionToString();
+
+ String encodedAssertion = Base64UrlUtility.encode(assertion);
+
+ Map<String, String> extraParams = new HashMap<String, String>();
+ extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE, Constants.CLIENT_AUTH_SAML2_BEARER);
+ extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, encodedAssertion);
+
+ try {
+ OAuthClientUtils.getAccessToken(wc, new CustomGrant(), extraParams);
+ fail("Failure expected on a bad subject name");
+ } catch (OAuthServiceException ex) {
+ // expected
+ }
+ }
+
+ @Test
+ public void testSAMLUnsigned() throws Exception {
+ String address = "https://localhost:" + PORT + "/oauth2-auth/token";
+ WebClient wc = createWebClient(address);
+
+ String audienceURI = "https://localhost:" + PORT + "/oauth2-auth/token";
+ String assertion = OAuth2TestUtils.createToken(audienceURI, true, false);
+ String encodedAssertion = Base64UrlUtility.encode(assertion);
+
+ Map<String, String> extraParams = new HashMap<String, String>();
+ extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE, Constants.CLIENT_AUTH_SAML2_BEARER);
+ extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, encodedAssertion);
+
+ try {
+ OAuthClientUtils.getAccessToken(wc, new CustomGrant(), extraParams);
+ fail("Failure expected on an unsigned token");
+ } catch (Exception ex) {
+ // expected
+ }
+ }
+
+ @Test
+ public void testSAMLHolderOfKey() throws Exception {
+ String address = "https://localhost:" + PORT + "/oauth2-auth/token";
+ WebClient wc = createWebClient(address);
+
+ String audienceURI = "https://localhost:" + PORT + "/oauth2-auth/token";
+
+ // Create the SAML Assertion
+ SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(true);
+ samlCallbackHandler.setConfirmationMethod(SAML2Constants.CONF_HOLDER_KEY);
+ samlCallbackHandler.setSubjectName("alice");
+ samlCallbackHandler.setAudience(audienceURI);
+
+ SAMLCallback samlCallback = new SAMLCallback();
+ SAMLUtil.doSAMLCallback(samlCallbackHandler, samlCallback);
+
+ SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback);
+ if (samlCallback.isSignAssertion()) {
+ samlAssertion.signAssertion(
+ samlCallback.getIssuerKeyName(),
+ samlCallback.getIssuerKeyPassword(),
+ samlCallback.getIssuerCrypto(),
+ samlCallback.isSendKeyValue(),
+ samlCallback.getCanonicalizationAlgorithm(),
+ samlCallback.getSignatureAlgorithm()
+ );
+ }
+
+ String assertion = samlAssertion.assertionToString();
+
+ String encodedAssertion = Base64UrlUtility.encode(assertion);
+
+ Map<String, String> extraParams = new HashMap<String, String>();
+ extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE, Constants.CLIENT_AUTH_SAML2_BEARER);
+ extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, encodedAssertion);
+
+ try {
+ OAuthClientUtils.getAccessToken(wc, new CustomGrant(), extraParams);
+ fail("Failure expected on a bad subject confirmation method");
+ } catch (OAuthServiceException ex) {
+ // expected
+ }
+ }
+
+ @Test
+ public void testJWTBadSubjectName() throws Exception {
+ String address = "https://localhost:" + PORT + "/oauth2-auth-jwt/token";
+ WebClient wc = createWebClient(address);
+
+ // Create the JWT Token
+ String token = OAuth2TestUtils.createToken("resourceOwner", "bob", address, true, true);
+
+ Map<String, String> extraParams = new HashMap<String, String>();
+ extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE,
+ "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
+ extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, token);
+
+ try {
+ OAuthClientUtils.getAccessToken(wc, new CustomGrant(), extraParams);
+ fail("Failure expected on a bad subject name");
+ } catch (OAuthServiceException ex) {
+ // expected
+ }
+ }
+
+ @Test
+ public void testJWTUnsigned() throws Exception {
+ String address = "https://localhost:" + PORT + "/oauth2-auth-jwt/token";
+ WebClient wc = createWebClient(address);
+
+ // Create the JWT Token
+ String token = OAuth2TestUtils.createToken("resourceOwner", "alice", address,
+ true, false);
+
+ Map<String, String> extraParams = new HashMap<String, String>();
+ extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE,
+ "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
+ extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, token);
+
+ try {
+ OAuthClientUtils.getAccessToken(wc, new CustomGrant(), extraParams);
+ fail("Failure expected on an unsigned token");
+ } catch (Exception ex) {
+ // expected
+ }
+ }
+
+ @Test
+ public void testJWTNoIssuer() throws Exception {
+ String address = "https://localhost:" + PORT + "/oauth2-auth-jwt/token";
+ WebClient wc = createWebClient(address);
+
+ // Create the JWT Token
+ String token = OAuth2TestUtils.createToken(null, "alice", address, true, true);
+
+ Map<String, String> extraParams = new HashMap<String, String>();
+ extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE,
+ "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
+ extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, token);
+
+ try {
+ OAuthClientUtils.getAccessToken(wc, new CustomGrant(), extraParams);
+ fail("Failure expected on no issuer");
+ } catch (Exception ex) {
+ // expected
+ }
+ }
+
+ @Test
+ public void testJWTNoExpiry() throws Exception {
+ String address = "https://localhost:" + PORT + "/oauth2-auth-jwt/token";
+ WebClient wc = createWebClient(address);
+
+ // Create the JWT Token
+ String token = OAuth2TestUtils.createToken("resourceOwner", "alice",
+ address, false, true);
+
+ Map<String, String> extraParams = new HashMap<String, String>();
+ extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE,
+ "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
+ extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, token);
+
+ try {
+ OAuthClientUtils.getAccessToken(wc, new CustomGrant(), extraParams);
+ fail("Failure expected on no expiry");
+ } catch (Exception ex) {
+ // expected
+ }
+ }
+
+ @Test
+ public void testJWTBadAudienceRestriction() throws Exception {
+ String address = "https://localhost:" + PORT + "/oauth2-auth-jwt/token";
+ WebClient wc = createWebClient(address);
+
+ // Create the JWT Token
+ String token = OAuth2TestUtils.createToken("resourceOwner", "alice",
+ address + "/badtoken", true, true);
+
+ Map<String, String> extraParams = new HashMap<String, String>();
+ extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE,
+ "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
+ extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, token);
+
+ try {
+ OAuthClientUtils.getAccessToken(wc, new CustomGrant(), extraParams);
+ fail("Failure expected on a bad audience restriction");
+ } catch (Exception ex) {
+ // expected
+ }
+ }
+
+ private WebClient createWebClient(String address) {
+ JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean();
+ bean.setAddress(address);
+
+ SpringBusFactory bf = new SpringBusFactory();
+ URL busFile = JAXRSOAuth2Test.class.getResource("client.xml");
+ Bus springBus = bf.createBus(busFile.toString());
+ bean.setBus(springBus);
+
+ WebClient wc = bean.createWebClient();
+ wc.type(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_JSON);
+ return wc;
+ }
+
+ private WebClient createWebClientWithProps(String address) {
+ JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean();
+ bean.setAddress(address);
+
+ SpringBusFactory bf = new SpringBusFactory();
+ URL busFile = JAXRSOAuth2Test.class.getResource("client.xml");
+ Bus springBus = bf.createBus(busFile.toString());
+ bean.setBus(springBus);
+
+ Map<String, Object> properties = new HashMap<String, Object>();
+ properties.put("security.callback-handler",
+ "org.apache.cxf.systest.jaxrs.security.saml.KeystorePasswordCallback");
+
+ SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(true);
+ samlCallbackHandler.setIssuer("alice");
+ String audienceURI = "https://localhost:" + PORT + "/oauth2-auth/token";
+ samlCallbackHandler.setAudience(audienceURI);
+ properties.put("security.saml-callback-handler", samlCallbackHandler);
+
+ properties.put("security.signature.username", "alice");
+ properties.put("security.signature.properties", CRYPTO_RESOURCE_PROPERTIES);
+ bean.setProperties(properties);
+
+ bean.getOutInterceptors().add(new Saml2BearerAuthOutInterceptor());
+
+ WebClient wc = bean.createWebClient();
+ wc.type(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_JSON);
+ return wc;
+ }
+
+ private static class CustomGrant implements AccessTokenGrant {
+
+ private static final long serialVersionUID = -4007538779198315873L;
+
+ @Override
+ public String getType() {
+ return "custom_grant";
+ }
+
+ @Override
+ public MultivaluedMap<String, String> toMap() {
+ MultivaluedMap<String, String> map = new MetadataMap<String, String>();
+ map.putSingle(OAuthConstants.GRANT_TYPE, "custom_grant");
+ return map;
+ }
+
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cxf/blob/2e8219cf/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/OAuthDataProviderImpl.java
----------------------------------------------------------------------
diff --git a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/OAuthDataProviderImpl.java b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/OAuthDataProviderImpl.java
deleted file mode 100644
index 0ae9708..0000000
--- a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/OAuthDataProviderImpl.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/**
- * 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.cxf.systest.jaxrs.security.oauth2.grants;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import org.apache.cxf.rs.security.oauth2.common.Client;
-import org.apache.cxf.rs.security.oauth2.common.OAuthPermission;
-import org.apache.cxf.rs.security.oauth2.grants.code.DefaultEHCacheCodeDataProvider;
-import org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException;
-
-/**
- * Extend the DefaultEHCacheCodeDataProvider to allow refreshing of tokens
- */
-public class OAuthDataProviderImpl extends DefaultEHCacheCodeDataProvider {
-
- public OAuthDataProviderImpl() {
- Client client = new Client("consumer-id", "this-is-a-secret", true);
- client.setRedirectUris(Collections.singletonList("http://www.blah.apache.org"));
-
- client.getAllowedGrantTypes().add("authorization_code");
- client.getAllowedGrantTypes().add("refresh_token");
- client.getAllowedGrantTypes().add("implicit");
- client.getAllowedGrantTypes().add("password");
- client.getAllowedGrantTypes().add("client_credentials");
- client.getAllowedGrantTypes().add("urn:ietf:params:oauth:grant-type:saml2-bearer");
- client.getAllowedGrantTypes().add("urn:ietf:params:oauth:grant-type:jwt-bearer");
-
- client.getRegisteredScopes().add("read_balance");
- client.getRegisteredScopes().add("create_balance");
- client.getRegisteredScopes().add("read_data");
-
- this.setClient(client);
- }
-
- @Override
- protected boolean isRefreshTokenSupported(List<String> theScopes) {
- return true;
- }
-
- @Override
- public List<OAuthPermission> convertScopeToPermissions(Client client, List<String> requestedScopes) {
- if (requestedScopes.isEmpty()) {
- return Collections.emptyList();
- }
-
- List<OAuthPermission> permissions = new ArrayList<>();
- for (String requestedScope : requestedScopes) {
- if ("read_balance".equals(requestedScope)) {
- OAuthPermission permission = new OAuthPermission();
- permission.setHttpVerbs(Collections.singletonList("GET"));
- List<String> uris = new ArrayList<>();
- String partnerAddress = "/partners/balance/*";
- uris.add(partnerAddress);
- permission.setUris(uris);
-
- permissions.add(permission);
- } else if ("create_balance".equals(requestedScope)) {
- OAuthPermission permission = new OAuthPermission();
- permission.setHttpVerbs(Collections.singletonList("POST"));
- List<String> uris = new ArrayList<>();
- String partnerAddress = "/partners/balance/*";
- uris.add(partnerAddress);
- permission.setUris(uris);
-
- permissions.add(permission);
- } else if ("read_data".equals(requestedScope)) {
- OAuthPermission permission = new OAuthPermission();
- permission.setHttpVerbs(Collections.singletonList("GET"));
- List<String> uris = new ArrayList<>();
- String partnerAddress = "/partners/data/*";
- uris.add(partnerAddress);
- permission.setUris(uris);
-
- permissions.add(permission);
- } else {
- throw new OAuthServiceException("invalid_scope");
- }
- }
-
- return permissions;
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cxf/blob/2e8219cf/systests/rs-security/src/test/resources/org/apache/cxf/systest/jaxrs/security/oauth2/client.xml
----------------------------------------------------------------------
diff --git a/systests/rs-security/src/test/resources/org/apache/cxf/systest/jaxrs/security/oauth2/client.xml b/systests/rs-security/src/test/resources/org/apache/cxf/systest/jaxrs/security/oauth2/client.xml
deleted file mode 100644
index 13eaea1..0000000
--- a/systests/rs-security/src/test/resources/org/apache/cxf/systest/jaxrs/security/oauth2/client.xml
+++ /dev/null
@@ -1,38 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- 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.
--->
-<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:http="http://cxf.apache.org/transports/http/configuration" xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:cxf="http://cxf.apache.org/core" xmlns:p="http://cxf.apache.org/policy" xmlns:sec="http://cxf.apache.org/configuration/security" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd http://cxf.apache.org/transports/http/configuration http://cxf.apache.org/schemas/configuration/http-conf.xsd http://cxf.apache.org/configuration/security http://cxf.apache.org/schemas/configuration/security.xsd http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd http://cxf.apache.org/policy http://cxf.apache.org/schemas/poli
cy.xsd">
- <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"/>
- <cxf:bus>
- <cxf:features>
- <cxf:logging/>
- </cxf:features>
- </cxf:bus>
- <http:conduit name="https://localhost.*">
- <http:client ConnectionTimeout="3000000" ReceiveTimeout="3000000"/>
- <http:tlsClientParameters disableCNCheck="true">
- <sec:keyManagers keyPassword="password">
- <sec:keyStore type="JKS" password="password" file="src/test/java/org/apache/cxf/systest/http/resources/Morpit.jks"/>
- </sec:keyManagers>
- <sec:trustManagers>
- <sec:keyStore type="JKS" password="password" file="src/test/java/org/apache/cxf/systest/http/resources/Truststore.jks"/>
- </sec:trustManagers>
- </http:tlsClientParameters>
- </http:conduit>
-</beans>
http://git-wip-us.apache.org/repos/asf/cxf/blob/2e8219cf/systests/rs-security/src/test/resources/org/apache/cxf/systest/jaxrs/security/oauth2/filters/oauth20-server.xml
----------------------------------------------------------------------
diff --git a/systests/rs-security/src/test/resources/org/apache/cxf/systest/jaxrs/security/oauth2/filters/oauth20-server.xml b/systests/rs-security/src/test/resources/org/apache/cxf/systest/jaxrs/security/oauth2/filters/oauth20-server.xml
index 3169727..ce7a8d9 100644
--- a/systests/rs-security/src/test/resources/org/apache/cxf/systest/jaxrs/security/oauth2/filters/oauth20-server.xml
+++ b/systests/rs-security/src/test/resources/org/apache/cxf/systest/jaxrs/security/oauth2/filters/oauth20-server.xml
@@ -62,7 +62,7 @@ under the License.
</httpj:engine>
</httpj:engine-factory>
- <bean id="oauthProvider" class="org.apache.cxf.systest.jaxrs.security.oauth2.filters.OAuthDataProviderImpl" />
+ <bean id="oauthProvider" class="org.apache.cxf.systest.jaxrs.security.oauth2.common.OAuthDataProviderImpl" />
<bean id="authorizationService" class="org.apache.cxf.rs.security.oauth2.services.AuthorizationCodeGrantService">
<property name="dataProvider" ref="oauthProvider"/>
@@ -89,8 +89,8 @@ under the License.
<property name="dataProvider" ref="oauthProvider"/>
</bean>
- <bean id="callbackHandler" class="org.apache.cxf.systest.jaxrs.security.oauth2.grants.CallbackHandlerImpl"/>
- <bean id="basicAuthFilter" class="org.apache.cxf.systest.jaxrs.security.oauth2.grants.BasicAuthFilter">
+ <bean id="callbackHandler" class="org.apache.cxf.systest.jaxrs.security.oauth2.common.CallbackHandlerImpl"/>
+ <bean id="basicAuthFilter" class="org.apache.cxf.systest.jaxrs.security.oauth2.common.BasicAuthFilter">
<property name="callbackHandler" ref="callbackHandler"/>
</bean>
http://git-wip-us.apache.org/repos/asf/cxf/blob/2e8219cf/systests/rs-security/src/test/resources/org/apache/cxf/systest/jaxrs/security/oauth2/grants/grants-negative-server.xml
----------------------------------------------------------------------
diff --git a/systests/rs-security/src/test/resources/org/apache/cxf/systest/jaxrs/security/oauth2/grants/grants-negative-server.xml b/systests/rs-security/src/test/resources/org/apache/cxf/systest/jaxrs/security/oauth2/grants/grants-negative-server.xml
index 5b367f6..75aa22f 100644
--- a/systests/rs-security/src/test/resources/org/apache/cxf/systest/jaxrs/security/oauth2/grants/grants-negative-server.xml
+++ b/systests/rs-security/src/test/resources/org/apache/cxf/systest/jaxrs/security/oauth2/grants/grants-negative-server.xml
@@ -62,7 +62,7 @@ under the License.
</httpj:engine>
</httpj:engine-factory>
- <bean id="oauthProvider" class="org.apache.cxf.systest.jaxrs.security.oauth2.grants.OAuthDataProviderImpl" />
+ <bean id="oauthProvider" class="org.apache.cxf.systest.jaxrs.security.oauth2.common.OAuthDataProviderImpl" />
<bean id="authorizationService" class="org.apache.cxf.rs.security.oauth2.services.AuthorizationCodeGrantService">
<property name="dataProvider" ref="oauthProvider"/>
@@ -110,8 +110,8 @@ under the License.
</property>
</bean>
- <bean id="callbackHandler" class="org.apache.cxf.systest.jaxrs.security.oauth2.grants.CallbackHandlerImpl"/>
- <bean id="basicAuthFilter" class="org.apache.cxf.systest.jaxrs.security.oauth2.grants.BasicAuthFilter">
+ <bean id="callbackHandler" class="org.apache.cxf.systest.jaxrs.security.oauth2.common.CallbackHandlerImpl"/>
+ <bean id="basicAuthFilter" class="org.apache.cxf.systest.jaxrs.security.oauth2.common.BasicAuthFilter">
<property name="callbackHandler" ref="callbackHandler"/>
</bean>
http://git-wip-us.apache.org/repos/asf/cxf/blob/2e8219cf/systests/rs-security/src/test/resources/org/apache/cxf/systest/jaxrs/security/oauth2/grants/grants-server.xml
----------------------------------------------------------------------
diff --git a/systests/rs-security/src/test/resources/org/apache/cxf/systest/jaxrs/security/oauth2/grants/grants-server.xml b/systests/rs-security/src/test/resources/org/apache/cxf/systest/jaxrs/security/oauth2/grants/grants-server.xml
index 3ef86fb..ccfa370 100644
--- a/systests/rs-security/src/test/resources/org/apache/cxf/systest/jaxrs/security/oauth2/grants/grants-server.xml
+++ b/systests/rs-security/src/test/resources/org/apache/cxf/systest/jaxrs/security/oauth2/grants/grants-server.xml
@@ -62,7 +62,7 @@ under the License.
</httpj:engine>
</httpj:engine-factory>
- <bean id="oauthProvider" class="org.apache.cxf.systest.jaxrs.security.oauth2.grants.OAuthDataProviderImpl" />
+ <bean id="oauthProvider" class="org.apache.cxf.systest.jaxrs.security.oauth2.common.OAuthDataProviderImpl" />
<bean id="authorizationService" class="org.apache.cxf.rs.security.oauth2.services.AuthorizationCodeGrantService">
<property name="dataProvider" ref="oauthProvider"/>
@@ -110,8 +110,8 @@ under the License.
</property>
</bean>
- <bean id="callbackHandler" class="org.apache.cxf.systest.jaxrs.security.oauth2.grants.CallbackHandlerImpl"/>
- <bean id="basicAuthFilter" class="org.apache.cxf.systest.jaxrs.security.oauth2.grants.BasicAuthFilter">
+ <bean id="callbackHandler" class="org.apache.cxf.systest.jaxrs.security.oauth2.common.CallbackHandlerImpl"/>
+ <bean id="basicAuthFilter" class="org.apache.cxf.systest.jaxrs.security.oauth2.common.BasicAuthFilter">
<property name="callbackHandler" ref="callbackHandler"/>
</bean>
http://git-wip-us.apache.org/repos/asf/cxf/blob/2e8219cf/systests/rs-security/src/test/resources/org/apache/cxf/systest/jaxrs/security/oauth2/grants/server.xml
----------------------------------------------------------------------
diff --git a/systests/rs-security/src/test/resources/org/apache/cxf/systest/jaxrs/security/oauth2/grants/server.xml b/systests/rs-security/src/test/resources/org/apache/cxf/systest/jaxrs/security/oauth2/grants/server.xml
new file mode 100644
index 0000000..2b3d821
--- /dev/null
+++ b/systests/rs-security/src/test/resources/org/apache/cxf/systest/jaxrs/security/oauth2/grants/server.xml
@@ -0,0 +1,127 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+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.
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:http="http://cxf.apache.org/transports/http/configuration"
+ xmlns:httpj="http://cxf.apache.org/transports/http-jetty/configuration"
+ xmlns:sec="http://cxf.apache.org/configuration/security"
+ xmlns:cxf="http://cxf.apache.org/core"
+ xmlns:jaxrs="http://cxf.apache.org/jaxrs"
+ xmlns:util="http://www.springframework.org/schema/util"
+ xsi:schemaLocation="http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
+ http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
+ http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
+ http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
+ http://cxf.apache.org/transports/http/configuration http://cxf.apache.org/schemas/configuration/http-conf.xsd
+ http://cxf.apache.org/transports/http-jetty/configuration http://cxf.apache.org/schemas/configuration/http-jetty.xsd
+ http://cxf.apache.org/configuration/security http://cxf.apache.org/schemas/configuration/security.xsd">
+ <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"/>
+ <cxf:bus>
+ <cxf:features>
+ <cxf:logging/>
+ </cxf:features>
+ <cxf:properties>
+ <entry key="org.apache.cxf.jaxrs.bus.providers" value-ref="busProviders"/>
+ </cxf:properties>
+ </cxf:bus>
+ <!-- providers -->
+ <util:list id="busProviders">
+ <ref bean="oauthJson"/>
+ </util:list>
+ <httpj:engine-factory id="port-9095-tls-config">
+ <httpj:engine port="${testutil.ports.jaxrs-oauth2}">
+ <httpj:tlsServerParameters>
+ <sec:keyManagers keyPassword="password">
+ <sec:keyStore type="JKS" password="password" file="src/test/java/org/apache/cxf/systest/http/resources/Bethal.jks"/>
+ </sec:keyManagers>
+ <sec:trustManagers>
+ <sec:keyStore type="JKS" password="password" file="src/test/java/org/apache/cxf/systest/http/resources/Truststore.jks"/>
+ </sec:trustManagers>
+ <sec:clientAuthentication want="true" required="true"/>
+ </httpj:tlsServerParameters>
+ </httpj:engine>
+ </httpj:engine-factory>
+ <bean id="dataProvider" class="org.apache.cxf.systest.jaxrs.security.oauth2.common.OAuthDataProviderImpl"/>
+ <bean id="samlGrantHandler" class="org.apache.cxf.rs.security.oauth2.grants.saml.Saml2BearerGrantHandler">
+ <property name="dataProvider" ref="dataProvider"/>
+ </bean>
+ <bean id="jwtGrantHandler" class="org.apache.cxf.rs.security.oauth2.grants.jwt.JwtBearerGrantHandler">
+ <property name="dataProvider" ref="dataProvider"/>
+ </bean>
+
+ <bean id="samlAuthHandler" class="org.apache.cxf.rs.security.oauth2.auth.saml.Saml2BearerAuthHandler"/>
+ <bean id="jwtAuthHandler" class="org.apache.cxf.rs.security.oauth2.grants.jwt.JwtBearerAuthHandler"/>
+
+ <bean id="customGrantHandler" class="org.apache.cxf.systest.jaxrs.security.oauth2.grants.CustomGrantHandler">
+ <property name="dataProvider" ref="dataProvider"/>
+ </bean>
+ <bean id="oauthJson" class="org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider"/>
+ <bean id="serviceBean" class="org.apache.cxf.rs.security.oauth2.services.AccessTokenService">
+ <property name="dataProvider" ref="dataProvider"/>
+ <property name="grantHandlers">
+ <list>
+ <ref bean="samlGrantHandler"/>
+ <ref bean="jwtGrantHandler"/>
+ <ref bean="customGrantHandler"/>
+ </list>
+ </property>
+ </bean>
+ <jaxrs:server address="https://localhost:${testutil.ports.jaxrs-oauth2}/oauth2">
+ <jaxrs:serviceBeans>
+ <ref bean="serviceBean"/>
+ </jaxrs:serviceBeans>
+ <jaxrs:properties>
+ <entry key="security.signature.properties" value="org/apache/cxf/systest/jaxrs/security/alice.properties"/>
+ <entry key="rs.security.keystore.type" value="jks" />
+ <entry key="rs.security.keystore.alias" value="alice"/>
+ <entry key="rs.security.keystore.password" value="password"/>
+ <entry key="rs.security.keystore.file"
+ value="org/apache/cxf/systest/jaxrs/security/certs/alice.jks" />
+ <entry key="rs.security.signature.algorithm" value="RS256" />
+ </jaxrs:properties>
+ </jaxrs:server>
+ <jaxrs:server address="https://localhost:${testutil.ports.jaxrs-oauth2}/oauth2-auth">
+ <jaxrs:serviceBeans>
+ <ref bean="serviceBean"/>
+ </jaxrs:serviceBeans>
+ <jaxrs:providers>
+ <ref bean="samlAuthHandler"/>
+ </jaxrs:providers>
+ <jaxrs:properties>
+ <entry key="security.signature.properties" value="org/apache/cxf/systest/jaxrs/security/alice.properties"/>
+ </jaxrs:properties>
+ </jaxrs:server>
+ <jaxrs:server address="https://localhost:${testutil.ports.jaxrs-oauth2}/oauth2-auth-jwt">
+ <jaxrs:serviceBeans>
+ <ref bean="serviceBean"/>
+ </jaxrs:serviceBeans>
+ <jaxrs:providers>
+ <ref bean="jwtAuthHandler"/>
+ </jaxrs:providers>
+ <jaxrs:properties>
+ <entry key="rs.security.keystore.type" value="jks" />
+ <entry key="rs.security.keystore.alias" value="alice"/>
+ <entry key="rs.security.keystore.password" value="password"/>
+ <entry key="rs.security.keystore.file"
+ value="org/apache/cxf/systest/jaxrs/security/certs/alice.jks" />
+ <entry key="rs.security.signature.algorithm" value="RS256" />
+ </jaxrs:properties>
+ </jaxrs:server>
+</beans>
http://git-wip-us.apache.org/repos/asf/cxf/blob/2e8219cf/systests/rs-security/src/test/resources/org/apache/cxf/systest/jaxrs/security/oauth2/server.xml
----------------------------------------------------------------------
diff --git a/systests/rs-security/src/test/resources/org/apache/cxf/systest/jaxrs/security/oauth2/server.xml b/systests/rs-security/src/test/resources/org/apache/cxf/systest/jaxrs/security/oauth2/server.xml
index 75fb048..1de107b 100644
--- a/systests/rs-security/src/test/resources/org/apache/cxf/systest/jaxrs/security/oauth2/server.xml
+++ b/systests/rs-security/src/test/resources/org/apache/cxf/systest/jaxrs/security/oauth2/server.xml
@@ -58,7 +58,7 @@ under the License.
</httpj:tlsServerParameters>
</httpj:engine>
</httpj:engine-factory>
- <bean id="dataProvider" class="org.apache.cxf.systest.jaxrs.security.oauth2.OAuthDataProviderImpl"/>
+ <bean id="dataProvider" class="org.apache.cxf.systest.jaxrs.security.oauth2.common.OAuthDataProviderImpl"/>
<bean id="samlGrantHandler" class="org.apache.cxf.rs.security.oauth2.grants.saml.Saml2BearerGrantHandler">
<property name="dataProvider" ref="dataProvider"/>
</bean>
[4/5] cxf git commit: Adding more OAuth 2 filter system tests
Posted by co...@apache.org.
Adding more OAuth 2 filter system tests
Project: http://git-wip-us.apache.org/repos/asf/cxf/repo
Commit: http://git-wip-us.apache.org/repos/asf/cxf/commit/2fd41e11
Tree: http://git-wip-us.apache.org/repos/asf/cxf/tree/2fd41e11
Diff: http://git-wip-us.apache.org/repos/asf/cxf/diff/2fd41e11
Branch: refs/heads/master
Commit: 2fd41e1170967f4426a2f9fa1ca722c6e58fc313
Parents: 5916997
Author: Colm O hEigeartaigh <co...@apache.org>
Authored: Wed Jan 20 12:24:46 2016 +0000
Committer: Colm O hEigeartaigh <co...@apache.org>
Committed: Wed Jan 20 15:00:59 2016 +0000
----------------------------------------------------------------------
.../oauth2/filters/OAuth2FiltersTest.java | 189 +++++++++++++++++++
.../oauth2/filters/OAuthDataProviderImpl.java | 10 +
2 files changed, 199 insertions(+)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cxf/blob/2fd41e11/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/filters/OAuth2FiltersTest.java
----------------------------------------------------------------------
diff --git a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/filters/OAuth2FiltersTest.java b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/filters/OAuth2FiltersTest.java
index 79a708a..e69ab9c 100644
--- a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/filters/OAuth2FiltersTest.java
+++ b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/filters/OAuth2FiltersTest.java
@@ -23,6 +23,7 @@ import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
+import java.util.UUID;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.Response;
@@ -89,6 +90,194 @@ public class OAuth2FiltersTest extends AbstractBusClientServerTestBase {
assertEquals(returnedBook.getName(), "book");
assertEquals(returnedBook.getId(), 123L);
}
+
+ @org.junit.Test
+ public void testServiceWithFakeToken() throws Exception {
+ URL busFile = OAuth2FiltersTest.class.getResource("client.xml");
+
+ // Now invoke on the service with the faked access token
+ String address = "https://localhost:" + PORT + "/secured/bookstore/books";
+ WebClient client = WebClient.create(address, setupProviders(), busFile.toString());
+ client.header("Authorization", "Bearer " + UUID.randomUUID().toString());
+
+ Response response = client.post(new Book("book", 123L));
+ assertNotEquals(response.getStatus(), 200);
+ }
+
+ @org.junit.Test
+ public void testServiceWithNoToken() throws Exception {
+ URL busFile = OAuth2FiltersTest.class.getResource("client.xml");
+
+ // Now invoke on the service with the faked access token
+ String address = "https://localhost:" + PORT + "/secured/bookstore/books";
+ WebClient client = WebClient.create(address, setupProviders(), busFile.toString());
+
+ Response response = client.post(new Book("book", 123L));
+ assertNotEquals(response.getStatus(), 200);
+ }
+
+ @org.junit.Test
+ public void testServiceWithEmptyToken() throws Exception {
+ URL busFile = OAuth2FiltersTest.class.getResource("client.xml");
+
+ // Now invoke on the service with the faked access token
+ String address = "https://localhost:" + PORT + "/secured/bookstore/books";
+ WebClient client = WebClient.create(address, setupProviders(), busFile.toString());
+ client.header("Authorization", "Bearer ");
+
+ Response response = client.post(new Book("book", 123L));
+ assertNotEquals(response.getStatus(), 200);
+ }
+
+ @org.junit.Test
+ public void testServiceWithTokenAndScope() throws Exception {
+ URL busFile = OAuth2FiltersTest.class.getResource("client.xml");
+
+ // Get Authorization Code
+ String oauthService = "https://localhost:" + OAUTH_PORT + "/services/";
+
+ WebClient oauthClient = WebClient.create(oauthService, setupProviders(), "alice",
+ "security", busFile.toString());
+ // Save the Cookie for the second request...
+ WebClient.getConfig(oauthClient).getRequestContext().put(
+ org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
+
+ String code = getAuthorizationCode(oauthClient, "create_book");
+ assertNotNull(code);
+
+ // Now get the access token
+ oauthClient = WebClient.create(oauthService, setupProviders(), "consumer-id",
+ "this-is-a-secret", busFile.toString());
+ // Save the Cookie for the second request...
+ WebClient.getConfig(oauthClient).getRequestContext().put(
+ org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
+
+ ClientAccessToken accessToken = getAccessTokenWithAuthorizationCode(oauthClient, code);
+ assertNotNull(accessToken.getTokenKey());
+
+ // Now invoke on the service with the access token
+ String address = "https://localhost:" + PORT + "/secured/bookstore/books";
+ WebClient client = WebClient.create(address, setupProviders(), busFile.toString());
+ client.header("Authorization", "Bearer " + accessToken.getTokenKey());
+
+ Response response = client.post(new Book("book", 123L));
+ assertEquals(response.getStatus(), 200);
+
+ Book returnedBook = response.readEntity(Book.class);
+ assertEquals(returnedBook.getName(), "book");
+ assertEquals(returnedBook.getId(), 123L);
+ }
+
+ @org.junit.Test
+ public void testServiceWithTokenAndIncorrectScopeVerb() throws Exception {
+ URL busFile = OAuth2FiltersTest.class.getResource("client.xml");
+
+ // Get Authorization Code
+ String oauthService = "https://localhost:" + OAUTH_PORT + "/services/";
+
+ WebClient oauthClient = WebClient.create(oauthService, setupProviders(), "alice",
+ "security", busFile.toString());
+ // Save the Cookie for the second request...
+ WebClient.getConfig(oauthClient).getRequestContext().put(
+ org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
+
+ String code = getAuthorizationCode(oauthClient, "read_book");
+ assertNotNull(code);
+
+ // Now get the access token
+ oauthClient = WebClient.create(oauthService, setupProviders(), "consumer-id",
+ "this-is-a-secret", busFile.toString());
+ // Save the Cookie for the second request...
+ WebClient.getConfig(oauthClient).getRequestContext().put(
+ org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
+
+ ClientAccessToken accessToken = getAccessTokenWithAuthorizationCode(oauthClient, code);
+ assertNotNull(accessToken.getTokenKey());
+
+ // Now invoke on the service with the access token
+ String address = "https://localhost:" + PORT + "/secured/bookstore/books";
+ WebClient client = WebClient.create(address, setupProviders(), busFile.toString());
+ client.header("Authorization", "Bearer " + accessToken.getTokenKey());
+
+ // We don't have the scope to post a book here
+ Response response = client.post(new Book("book", 123L));
+ assertNotEquals(response.getStatus(), 200);
+ }
+
+ @org.junit.Test
+ public void testServiceWithTokenAndIncorrectScopeURI() throws Exception {
+ URL busFile = OAuth2FiltersTest.class.getResource("client.xml");
+
+ // Get Authorization Code
+ String oauthService = "https://localhost:" + OAUTH_PORT + "/services/";
+
+ WebClient oauthClient = WebClient.create(oauthService, setupProviders(), "alice",
+ "security", busFile.toString());
+ // Save the Cookie for the second request...
+ WebClient.getConfig(oauthClient).getRequestContext().put(
+ org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
+
+ String code = getAuthorizationCode(oauthClient, "create_image");
+ assertNotNull(code);
+
+ // Now get the access token
+ oauthClient = WebClient.create(oauthService, setupProviders(), "consumer-id",
+ "this-is-a-secret", busFile.toString());
+ // Save the Cookie for the second request...
+ WebClient.getConfig(oauthClient).getRequestContext().put(
+ org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
+
+ ClientAccessToken accessToken = getAccessTokenWithAuthorizationCode(oauthClient, code);
+ assertNotNull(accessToken.getTokenKey());
+
+ // Now invoke on the service with the access token
+ String address = "https://localhost:" + PORT + "/secured/bookstore/books";
+ WebClient client = WebClient.create(address, setupProviders(), busFile.toString());
+ client.header("Authorization", "Bearer " + accessToken.getTokenKey());
+
+ // We don't have the scope to post a book here
+ Response response = client.post(new Book("book", 123L));
+ assertNotEquals(response.getStatus(), 200);
+ }
+
+ @org.junit.Test
+ public void testServiceWithTokenAndMultipleScopes() throws Exception {
+ URL busFile = OAuth2FiltersTest.class.getResource("client.xml");
+
+ // Get Authorization Code
+ String oauthService = "https://localhost:" + OAUTH_PORT + "/services/";
+
+ WebClient oauthClient = WebClient.create(oauthService, setupProviders(), "alice",
+ "security", busFile.toString());
+ // Save the Cookie for the second request...
+ WebClient.getConfig(oauthClient).getRequestContext().put(
+ org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
+
+ String code = getAuthorizationCode(oauthClient, "read_book create_image create_book");
+ assertNotNull(code);
+
+ // Now get the access token
+ oauthClient = WebClient.create(oauthService, setupProviders(), "consumer-id",
+ "this-is-a-secret", busFile.toString());
+ // Save the Cookie for the second request...
+ WebClient.getConfig(oauthClient).getRequestContext().put(
+ org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
+
+ ClientAccessToken accessToken = getAccessTokenWithAuthorizationCode(oauthClient, code);
+ assertNotNull(accessToken.getTokenKey());
+
+ // Now invoke on the service with the access token
+ String address = "https://localhost:" + PORT + "/secured/bookstore/books";
+ WebClient client = WebClient.create(address, setupProviders(), busFile.toString());
+ client.header("Authorization", "Bearer " + accessToken.getTokenKey());
+
+ Response response = client.post(new Book("book", 123L));
+ assertEquals(response.getStatus(), 200);
+
+ Book returnedBook = response.readEntity(Book.class);
+ assertEquals(returnedBook.getName(), "book");
+ assertEquals(returnedBook.getId(), 123L);
+ }
private List<Object> setupProviders() {
List<Object> providers = new ArrayList<Object>();
http://git-wip-us.apache.org/repos/asf/cxf/blob/2fd41e11/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/filters/OAuthDataProviderImpl.java
----------------------------------------------------------------------
diff --git a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/filters/OAuthDataProviderImpl.java b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/filters/OAuthDataProviderImpl.java
index 660d505..0426806 100644
--- a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/filters/OAuthDataProviderImpl.java
+++ b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/filters/OAuthDataProviderImpl.java
@@ -42,6 +42,7 @@ public class OAuthDataProviderImpl extends DefaultEHCacheCodeDataProvider {
client.getRegisteredScopes().add("read_book");
client.getRegisteredScopes().add("create_book");
+ client.getRegisteredScopes().add("create_image");
this.setClient(client);
}
@@ -77,6 +78,15 @@ public class OAuthDataProviderImpl extends DefaultEHCacheCodeDataProvider {
permission.setUris(uris);
permissions.add(permission);
+ } else if ("create_image".equals(requestedScope)) {
+ OAuthPermission permission = new OAuthPermission();
+ permission.setHttpVerbs(Collections.singletonList("POST"));
+ List<String> uris = new ArrayList<>();
+ String partnerAddress = "/secured/bookstore/image/*";
+ uris.add(partnerAddress);
+ permission.setUris(uris);
+
+ permissions.add(permission);
} else {
throw new OAuthServiceException("invalid_scope");
}
[2/5] cxf git commit: Reshuffle of the tests to share some common code
Posted by co...@apache.org.
http://git-wip-us.apache.org/repos/asf/cxf/blob/2e8219cf/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/filters/OAuth2FiltersTest.java
----------------------------------------------------------------------
diff --git a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/filters/OAuth2FiltersTest.java b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/filters/OAuth2FiltersTest.java
index e69ab9c..f79ba49 100644
--- a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/filters/OAuth2FiltersTest.java
+++ b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/filters/OAuth2FiltersTest.java
@@ -20,20 +20,14 @@
package org.apache.cxf.systest.jaxrs.security.oauth2.filters;
import java.net.URL;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
import java.util.UUID;
-import javax.ws.rs.core.Form;
import javax.ws.rs.core.Response;
import org.apache.cxf.jaxrs.client.WebClient;
-import org.apache.cxf.jaxrs.provider.json.JSONProvider;
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.systest.jaxrs.security.Book;
+import org.apache.cxf.systest.jaxrs.security.oauth2.common.OAuth2TestUtils;
import org.apache.cxf.testutil.common.AbstractBusClientServerTestBase;
import org.junit.BeforeClass;
@@ -59,28 +53,30 @@ public class OAuth2FiltersTest extends AbstractBusClientServerTestBase {
// Get Authorization Code
String oauthService = "https://localhost:" + OAUTH_PORT + "/services/";
- WebClient oauthClient = WebClient.create(oauthService, setupProviders(), "alice",
- "security", busFile.toString());
+ WebClient oauthClient = WebClient.create(oauthService, OAuth2TestUtils.setupProviders(),
+ "alice", "security", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(oauthClient).getRequestContext().put(
org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
- String code = getAuthorizationCode(oauthClient);
+ String code = OAuth2TestUtils.getAuthorizationCode(oauthClient);
assertNotNull(code);
// Now get the access token
- oauthClient = WebClient.create(oauthService, setupProviders(), "consumer-id",
- "this-is-a-secret", busFile.toString());
+ oauthClient = WebClient.create(oauthService, OAuth2TestUtils.setupProviders(),
+ "consumer-id", "this-is-a-secret", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(oauthClient).getRequestContext().put(
org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
- ClientAccessToken accessToken = getAccessTokenWithAuthorizationCode(oauthClient, code);
+ ClientAccessToken accessToken =
+ OAuth2TestUtils.getAccessTokenWithAuthorizationCode(oauthClient, code);
assertNotNull(accessToken.getTokenKey());
// Now invoke on the service with the access token
String address = "https://localhost:" + PORT + "/secured/bookstore/books";
- WebClient client = WebClient.create(address, setupProviders(), busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ busFile.toString());
client.header("Authorization", "Bearer " + accessToken.getTokenKey());
Response response = client.post(new Book("book", 123L));
@@ -97,7 +93,8 @@ public class OAuth2FiltersTest extends AbstractBusClientServerTestBase {
// Now invoke on the service with the faked access token
String address = "https://localhost:" + PORT + "/secured/bookstore/books";
- WebClient client = WebClient.create(address, setupProviders(), busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ busFile.toString());
client.header("Authorization", "Bearer " + UUID.randomUUID().toString());
Response response = client.post(new Book("book", 123L));
@@ -110,7 +107,8 @@ public class OAuth2FiltersTest extends AbstractBusClientServerTestBase {
// Now invoke on the service with the faked access token
String address = "https://localhost:" + PORT + "/secured/bookstore/books";
- WebClient client = WebClient.create(address, setupProviders(), busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ busFile.toString());
Response response = client.post(new Book("book", 123L));
assertNotEquals(response.getStatus(), 200);
@@ -122,7 +120,8 @@ public class OAuth2FiltersTest extends AbstractBusClientServerTestBase {
// Now invoke on the service with the faked access token
String address = "https://localhost:" + PORT + "/secured/bookstore/books";
- WebClient client = WebClient.create(address, setupProviders(), busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ busFile.toString());
client.header("Authorization", "Bearer ");
Response response = client.post(new Book("book", 123L));
@@ -136,28 +135,30 @@ public class OAuth2FiltersTest extends AbstractBusClientServerTestBase {
// Get Authorization Code
String oauthService = "https://localhost:" + OAUTH_PORT + "/services/";
- WebClient oauthClient = WebClient.create(oauthService, setupProviders(), "alice",
- "security", busFile.toString());
+ WebClient oauthClient = WebClient.create(oauthService, OAuth2TestUtils.setupProviders(),
+ "alice", "security", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(oauthClient).getRequestContext().put(
org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
- String code = getAuthorizationCode(oauthClient, "create_book");
+ String code = OAuth2TestUtils.getAuthorizationCode(oauthClient, "create_book");
assertNotNull(code);
// Now get the access token
- oauthClient = WebClient.create(oauthService, setupProviders(), "consumer-id",
- "this-is-a-secret", busFile.toString());
+ oauthClient = WebClient.create(oauthService, OAuth2TestUtils.setupProviders(),
+ "consumer-id", "this-is-a-secret", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(oauthClient).getRequestContext().put(
org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
- ClientAccessToken accessToken = getAccessTokenWithAuthorizationCode(oauthClient, code);
+ ClientAccessToken accessToken =
+ OAuth2TestUtils.getAccessTokenWithAuthorizationCode(oauthClient, code);
assertNotNull(accessToken.getTokenKey());
// Now invoke on the service with the access token
String address = "https://localhost:" + PORT + "/secured/bookstore/books";
- WebClient client = WebClient.create(address, setupProviders(), busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ busFile.toString());
client.header("Authorization", "Bearer " + accessToken.getTokenKey());
Response response = client.post(new Book("book", 123L));
@@ -175,28 +176,30 @@ public class OAuth2FiltersTest extends AbstractBusClientServerTestBase {
// Get Authorization Code
String oauthService = "https://localhost:" + OAUTH_PORT + "/services/";
- WebClient oauthClient = WebClient.create(oauthService, setupProviders(), "alice",
- "security", busFile.toString());
+ WebClient oauthClient = WebClient.create(oauthService, OAuth2TestUtils.setupProviders(),
+ "alice", "security", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(oauthClient).getRequestContext().put(
org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
- String code = getAuthorizationCode(oauthClient, "read_book");
+ String code = OAuth2TestUtils.getAuthorizationCode(oauthClient, "read_book");
assertNotNull(code);
// Now get the access token
- oauthClient = WebClient.create(oauthService, setupProviders(), "consumer-id",
- "this-is-a-secret", busFile.toString());
+ oauthClient = WebClient.create(oauthService, OAuth2TestUtils.setupProviders(),
+ "consumer-id", "this-is-a-secret", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(oauthClient).getRequestContext().put(
org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
- ClientAccessToken accessToken = getAccessTokenWithAuthorizationCode(oauthClient, code);
+ ClientAccessToken accessToken =
+ OAuth2TestUtils.getAccessTokenWithAuthorizationCode(oauthClient, code);
assertNotNull(accessToken.getTokenKey());
// Now invoke on the service with the access token
String address = "https://localhost:" + PORT + "/secured/bookstore/books";
- WebClient client = WebClient.create(address, setupProviders(), busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ busFile.toString());
client.header("Authorization", "Bearer " + accessToken.getTokenKey());
// We don't have the scope to post a book here
@@ -211,28 +214,30 @@ public class OAuth2FiltersTest extends AbstractBusClientServerTestBase {
// Get Authorization Code
String oauthService = "https://localhost:" + OAUTH_PORT + "/services/";
- WebClient oauthClient = WebClient.create(oauthService, setupProviders(), "alice",
- "security", busFile.toString());
+ WebClient oauthClient = WebClient.create(oauthService, OAuth2TestUtils.setupProviders(),
+ "alice", "security", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(oauthClient).getRequestContext().put(
org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
- String code = getAuthorizationCode(oauthClient, "create_image");
+ String code = OAuth2TestUtils.getAuthorizationCode(oauthClient, "create_image");
assertNotNull(code);
// Now get the access token
- oauthClient = WebClient.create(oauthService, setupProviders(), "consumer-id",
- "this-is-a-secret", busFile.toString());
+ oauthClient = WebClient.create(oauthService, OAuth2TestUtils.setupProviders(),
+ "consumer-id", "this-is-a-secret", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(oauthClient).getRequestContext().put(
org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
- ClientAccessToken accessToken = getAccessTokenWithAuthorizationCode(oauthClient, code);
+ ClientAccessToken accessToken =
+ OAuth2TestUtils.getAccessTokenWithAuthorizationCode(oauthClient, code);
assertNotNull(accessToken.getTokenKey());
// Now invoke on the service with the access token
String address = "https://localhost:" + PORT + "/secured/bookstore/books";
- WebClient client = WebClient.create(address, setupProviders(), busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ busFile.toString());
client.header("Authorization", "Bearer " + accessToken.getTokenKey());
// We don't have the scope to post a book here
@@ -247,28 +252,31 @@ public class OAuth2FiltersTest extends AbstractBusClientServerTestBase {
// Get Authorization Code
String oauthService = "https://localhost:" + OAUTH_PORT + "/services/";
- WebClient oauthClient = WebClient.create(oauthService, setupProviders(), "alice",
- "security", busFile.toString());
+ WebClient oauthClient = WebClient.create(oauthService, OAuth2TestUtils.setupProviders(),
+ "alice", "security", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(oauthClient).getRequestContext().put(
org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
- String code = getAuthorizationCode(oauthClient, "read_book create_image create_book");
+ String code = OAuth2TestUtils.getAuthorizationCode(oauthClient,
+ "read_book create_image create_book");
assertNotNull(code);
// Now get the access token
- oauthClient = WebClient.create(oauthService, setupProviders(), "consumer-id",
- "this-is-a-secret", busFile.toString());
+ oauthClient = WebClient.create(oauthService, OAuth2TestUtils.setupProviders(),
+ "consumer-id", "this-is-a-secret", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(oauthClient).getRequestContext().put(
org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
- ClientAccessToken accessToken = getAccessTokenWithAuthorizationCode(oauthClient, code);
+ ClientAccessToken accessToken =
+ OAuth2TestUtils.getAccessTokenWithAuthorizationCode(oauthClient, code);
assertNotNull(accessToken.getTokenKey());
// Now invoke on the service with the access token
String address = "https://localhost:" + PORT + "/secured/bookstore/books";
- WebClient client = WebClient.create(address, setupProviders(), busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ busFile.toString());
client.header("Authorization", "Bearer " + accessToken.getTokenKey());
Response response = client.post(new Book("book", 123L));
@@ -279,75 +287,4 @@ public class OAuth2FiltersTest extends AbstractBusClientServerTestBase {
assertEquals(returnedBook.getId(), 123L);
}
- private List<Object> setupProviders() {
- List<Object> providers = new ArrayList<Object>();
- JSONProvider<OAuthAuthorizationData> jsonP = new JSONProvider<OAuthAuthorizationData>();
- jsonP.setNamespaceMap(Collections.singletonMap("http://org.apache.cxf.rs.security.oauth",
- "ns2"));
- providers.add(jsonP);
- OAuthJSONProvider oauthProvider = new OAuthJSONProvider();
- providers.add(oauthProvider);
-
- return providers;
- }
-
- private String getAuthorizationCode(WebClient client) {
- return getAuthorizationCode(client, null);
- }
-
- private String getAuthorizationCode(WebClient client, String scope) {
- // Make initial authorization request
- client.type("application/json").accept("application/json");
- client.query("client_id", "consumer-id");
- client.query("redirect_uri", "http://www.blah.apache.org");
- client.query("response_type", "code");
- if (scope != null) {
- client.query("scope", scope);
- }
- client.path("authorize/");
- Response response = client.get();
-
- OAuthAuthorizationData authzData = response.readEntity(OAuthAuthorizationData.class);
-
- // Now call "decision" to get the authorization code grant
- client.path("decision");
- client.type("application/x-www-form-urlencoded");
-
- Form form = new Form();
- form.param("session_authenticity_token", authzData.getAuthenticityToken());
- form.param("client_id", authzData.getClientId());
- form.param("redirect_uri", authzData.getRedirectUri());
- if (authzData.getProposedScope() != null) {
- form.param("scope", authzData.getProposedScope());
- }
- form.param("oauthDecision", "allow");
-
- response = client.post(form);
- String location = response.getHeaderString("Location");
- return getSubstring(location, "code");
- }
-
- private ClientAccessToken getAccessTokenWithAuthorizationCode(WebClient client, String code) {
- client.type("application/x-www-form-urlencoded").accept("application/json");
- client.path("token");
-
- Form form = new Form();
- form.param("grant_type", "authorization_code");
- form.param("code", code);
- form.param("client_id", "consumer-id");
- Response response = client.post(form);
-
- return response.readEntity(ClientAccessToken.class);
- }
-
- private String getSubstring(String parentString, String substringName) {
- String foundString =
- parentString.substring(parentString.indexOf(substringName + "=") + (substringName + "=").length());
- int ampersandIndex = foundString.indexOf('&');
- if (ampersandIndex < 1) {
- ampersandIndex = foundString.length();
- }
- return foundString.substring(0, ampersandIndex);
- }
-
}
http://git-wip-us.apache.org/repos/asf/cxf/blob/2e8219cf/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/filters/OAuthDataProviderImpl.java
----------------------------------------------------------------------
diff --git a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/filters/OAuthDataProviderImpl.java b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/filters/OAuthDataProviderImpl.java
deleted file mode 100644
index 0426806..0000000
--- a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/filters/OAuthDataProviderImpl.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/**
- * 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.cxf.systest.jaxrs.security.oauth2.filters;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import org.apache.cxf.rs.security.oauth2.common.Client;
-import org.apache.cxf.rs.security.oauth2.common.OAuthPermission;
-import org.apache.cxf.rs.security.oauth2.grants.code.DefaultEHCacheCodeDataProvider;
-import org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException;
-
-/**
- * Extend the DefaultEHCacheCodeDataProvider to allow refreshing of tokens
- */
-public class OAuthDataProviderImpl extends DefaultEHCacheCodeDataProvider {
-
- public OAuthDataProviderImpl() {
- Client client = new Client("consumer-id", "this-is-a-secret", true);
- client.setRedirectUris(Collections.singletonList("http://www.blah.apache.org"));
-
- client.getAllowedGrantTypes().add("authorization_code");
- client.getAllowedGrantTypes().add("refresh_token");
- client.getAllowedGrantTypes().add("implicit");
-
- client.getRegisteredScopes().add("read_book");
- client.getRegisteredScopes().add("create_book");
- client.getRegisteredScopes().add("create_image");
-
- this.setClient(client);
- }
-
- @Override
- protected boolean isRefreshTokenSupported(List<String> theScopes) {
- return true;
- }
-
- @Override
- public List<OAuthPermission> convertScopeToPermissions(Client client, List<String> requestedScopes) {
- if (requestedScopes.isEmpty()) {
- return Collections.emptyList();
- }
-
- List<OAuthPermission> permissions = new ArrayList<>();
- for (String requestedScope : requestedScopes) {
- if ("read_book".equals(requestedScope)) {
- OAuthPermission permission = new OAuthPermission();
- permission.setHttpVerbs(Collections.singletonList("GET"));
- List<String> uris = new ArrayList<>();
- String partnerAddress = "/secured/bookstore/books/*";
- uris.add(partnerAddress);
- permission.setUris(uris);
-
- permissions.add(permission);
- } else if ("create_book".equals(requestedScope)) {
- OAuthPermission permission = new OAuthPermission();
- permission.setHttpVerbs(Collections.singletonList("POST"));
- List<String> uris = new ArrayList<>();
- String partnerAddress = "/secured/bookstore/books/*";
- uris.add(partnerAddress);
- permission.setUris(uris);
-
- permissions.add(permission);
- } else if ("create_image".equals(requestedScope)) {
- OAuthPermission permission = new OAuthPermission();
- permission.setHttpVerbs(Collections.singletonList("POST"));
- List<String> uris = new ArrayList<>();
- String partnerAddress = "/secured/bookstore/image/*";
- uris.add(partnerAddress);
- permission.setUris(uris);
-
- permissions.add(permission);
- } else {
- throw new OAuthServiceException("invalid_scope");
- }
- }
-
- return permissions;
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cxf/blob/2e8219cf/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/AuthorizationGrantNegativeTest.java
----------------------------------------------------------------------
diff --git a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/AuthorizationGrantNegativeTest.java b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/AuthorizationGrantNegativeTest.java
index 008c473..59a66bd 100644
--- a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/AuthorizationGrantNegativeTest.java
+++ b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/AuthorizationGrantNegativeTest.java
@@ -20,11 +20,9 @@
package org.apache.cxf.systest.jaxrs.security.oauth2.grants;
import java.net.URL;
-import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
-import java.util.List;
import java.util.Properties;
import javax.ws.rs.client.ResponseProcessingException;
@@ -33,23 +31,18 @@ import javax.ws.rs.core.Response;
import org.apache.cxf.common.util.Base64UrlUtility;
import org.apache.cxf.jaxrs.client.WebClient;
-import org.apache.cxf.jaxrs.provider.json.JSONProvider;
-import org.apache.cxf.rs.security.jose.jwa.SignatureAlgorithm;
import org.apache.cxf.rs.security.jose.jws.JwsHeaders;
import org.apache.cxf.rs.security.jose.jws.JwsJwtCompactProducer;
import org.apache.cxf.rs.security.jose.jws.JwsSignatureProvider;
import org.apache.cxf.rs.security.jose.jws.JwsUtils;
import org.apache.cxf.rs.security.jose.jwt.JwtClaims;
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.systest.jaxrs.security.oauth2.SamlCallbackHandler;
+import org.apache.cxf.systest.jaxrs.security.oauth2.common.OAuth2TestUtils;
+import org.apache.cxf.systest.jaxrs.security.oauth2.common.SamlCallbackHandler;
import org.apache.cxf.testutil.common.AbstractBusClientServerTestBase;
-import org.apache.wss4j.common.ext.WSSecurityException;
import org.apache.wss4j.common.saml.SAMLCallback;
import org.apache.wss4j.common.saml.SAMLUtil;
import org.apache.wss4j.common.saml.SamlAssertionWrapper;
-import org.apache.wss4j.common.saml.builder.SAML1Constants;
import org.apache.wss4j.common.saml.builder.SAML2Constants;
import org.junit.BeforeClass;
@@ -74,7 +67,8 @@ public class AuthorizationGrantNegativeTest extends AbstractBusClientServerTestB
URL busFile = AuthorizationGrantTest.class.getResource("client.xml");
String address = "https://localhost:" + PORT + "/services/";
- WebClient client = WebClient.create(address, setupProviders(), "alice", "security", busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "alice", "security", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(client).getRequestContext().put(
org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
@@ -101,7 +95,8 @@ public class AuthorizationGrantNegativeTest extends AbstractBusClientServerTestB
URL busFile = AuthorizationGrantTest.class.getResource("client.xml");
String address = "https://localhost:" + PORT + "/services/";
- WebClient client = WebClient.create(address, setupProviders(), "alice", "security", busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "alice", "security", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(client).getRequestContext().put(
org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
@@ -124,7 +119,8 @@ public class AuthorizationGrantNegativeTest extends AbstractBusClientServerTestB
URL busFile = AuthorizationGrantTest.class.getResource("client.xml");
String address = "https://localhost:" + PORT + "/services/";
- WebClient client = WebClient.create(address, setupProviders(), "alice", "security", busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "alice", "security", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(client).getRequestContext().put(
org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
@@ -151,7 +147,8 @@ public class AuthorizationGrantNegativeTest extends AbstractBusClientServerTestB
URL busFile = AuthorizationGrantTest.class.getResource("client.xml");
String address = "https://localhost:" + PORT + "/services/";
- WebClient client = WebClient.create(address, setupProviders(), "alice", "security", busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "alice", "security", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(client).getRequestContext().put(
org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
@@ -176,17 +173,19 @@ public class AuthorizationGrantNegativeTest extends AbstractBusClientServerTestB
URL busFile = AuthorizationGrantTest.class.getResource("client.xml");
String address = "https://localhost:" + PORT + "/services/";
- WebClient client = WebClient.create(address, setupProviders(), "alice", "security", busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "alice", "security", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(client).getRequestContext().put(
org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
// Get Authorization Code
- String code = getAuthorizationCode(client);
+ String code = OAuth2TestUtils.getAuthorizationCode(client);
assertNotNull(code);
// Now get the access token
- client = WebClient.create(address, setupProviders(), "consumer-id", "this-is-a-secret", busFile.toString());
+ client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "consumer-id", "this-is-a-secret", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(client).getRequestContext().put(
org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
@@ -219,22 +218,25 @@ public class AuthorizationGrantNegativeTest extends AbstractBusClientServerTestB
URL busFile = AuthorizationGrantTest.class.getResource("client.xml");
String address = "https://localhost:" + PORT + "/services/";
- WebClient client = WebClient.create(address, setupProviders(), "alice", "security", busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "alice", "security", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(client).getRequestContext().put(
org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
// Get Authorization Code
- String code = getAuthorizationCode(client, "read_balance");
+ String code = OAuth2TestUtils.getAuthorizationCode(client, "read_balance");
assertNotNull(code);
// Now get the access token
- client = WebClient.create(address, setupProviders(), "consumer-id", "this-is-a-secret", busFile.toString());
+ client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "consumer-id", "this-is-a-secret", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(client).getRequestContext().put(
org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
- ClientAccessToken accessToken = getAccessTokenWithAuthorizationCode(client, code);
+ ClientAccessToken accessToken =
+ OAuth2TestUtils.getAccessTokenWithAuthorizationCode(client, code);
assertNotNull(accessToken.getTokenKey());
assertNotNull(accessToken.getRefreshToken());
@@ -267,22 +269,25 @@ public class AuthorizationGrantNegativeTest extends AbstractBusClientServerTestB
URL busFile = AuthorizationGrantTest.class.getResource("client.xml");
String address = "https://localhost:" + PORT + "/services/";
- WebClient client = WebClient.create(address, setupProviders(), "alice", "security", busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "alice", "security", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(client).getRequestContext().put(
org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
// Get Authorization Code
- String code = getAuthorizationCode(client, "read_balance");
+ String code = OAuth2TestUtils.getAuthorizationCode(client, "read_balance");
assertNotNull(code);
// Now get the access token
- client = WebClient.create(address, setupProviders(), "consumer-id", "this-is-a-secret", busFile.toString());
+ client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "consumer-id", "this-is-a-secret", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(client).getRequestContext().put(
org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
- ClientAccessToken accessToken = getAccessTokenWithAuthorizationCode(client, code);
+ ClientAccessToken accessToken =
+ OAuth2TestUtils.getAccessTokenWithAuthorizationCode(client, code);
assertNotNull(accessToken.getTokenKey());
assertNotNull(accessToken.getRefreshToken());
@@ -320,17 +325,19 @@ public class AuthorizationGrantNegativeTest extends AbstractBusClientServerTestB
URL busFile = AuthorizationGrantTest.class.getResource("client.xml");
String address = "https://localhost:" + PORT + "/services/";
- WebClient client = WebClient.create(address, setupProviders(), "alice", "security", busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "alice", "security", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(client).getRequestContext().put(
org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
// Get Authorization Code
- String code = getAuthorizationCode(client);
+ String code = OAuth2TestUtils.getAuthorizationCode(client);
assertNotNull(code);
// Now get the access token
- client = WebClient.create(address, setupProviders(), "consumer-id", "this-is-a-secret", busFile.toString());
+ client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "consumer-id", "this-is-a-secret", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(client).getRequestContext().put(
org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
@@ -368,8 +375,9 @@ public class AuthorizationGrantNegativeTest extends AbstractBusClientServerTestB
URL busFile = AuthorizationGrantTest.class.getResource("client.xml");
String address = "https://localhost:" + PORT + "/services/";
- WebClient client = WebClient.create(address, setupProviders(), "consumer-id",
- "this-is-a-secret", busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "consumer-id", "this-is-a-secret",
+ busFile.toString());
// Get Access Token
client.type("application/x-www-form-urlencoded").accept("application/json");
@@ -405,8 +413,9 @@ public class AuthorizationGrantNegativeTest extends AbstractBusClientServerTestB
URL busFile = AuthorizationGrantTest.class.getResource("client.xml");
String address = "https://localhost:" + PORT + "/services/";
- WebClient client = WebClient.create(address, setupProviders(), "consumer-id",
- "this-is-a-secret", busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "consumer-id", "this-is-a-secret",
+ busFile.toString());
// Get Access Token
client.type("application/x-www-form-urlencoded").accept("application/json");
@@ -463,10 +472,11 @@ public class AuthorizationGrantNegativeTest extends AbstractBusClientServerTestB
URL busFile = AuthorizationGrantNegativeTest.class.getResource("client.xml");
String address = "https://localhost:" + PORT + "/services/";
- WebClient client = WebClient.create(address, setupProviders(), "alice", "security", busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "alice", "security", busFile.toString());
// Create the SAML Assertion
- String assertion = createToken(address + "token", false, true);
+ String assertion = OAuth2TestUtils.createToken(address + "token", false, true);
// Get Access Token
client.type("application/x-www-form-urlencoded").accept("application/json");
@@ -491,10 +501,11 @@ public class AuthorizationGrantNegativeTest extends AbstractBusClientServerTestB
URL busFile = AuthorizationGrantNegativeTest.class.getResource("client.xml");
String address = "https://localhost:" + PORT + "/services/";
- WebClient client = WebClient.create(address, setupProviders(), "alice", "security", busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "alice", "security", busFile.toString());
// Create the SAML Assertion
- String assertion = createToken(address + "token2", true, true);
+ String assertion = OAuth2TestUtils.createToken(address + "token2", true, true);
// Get Access Token
client.type("application/x-www-form-urlencoded").accept("application/json");
@@ -519,10 +530,11 @@ public class AuthorizationGrantNegativeTest extends AbstractBusClientServerTestB
URL busFile = AuthorizationGrantNegativeTest.class.getResource("client.xml");
String address = "https://localhost:" + PORT + "/services/";
- WebClient client = WebClient.create(address, setupProviders(), "alice", "security", busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "alice", "security", busFile.toString());
// Create the SAML Assertion
- String assertion = createToken(address + "token", true, false);
+ String assertion = OAuth2TestUtils.createToken(address + "token", true, false);
// Get Access Token
client.type("application/x-www-form-urlencoded").accept("application/json");
@@ -547,7 +559,8 @@ public class AuthorizationGrantNegativeTest extends AbstractBusClientServerTestB
URL busFile = AuthorizationGrantNegativeTest.class.getResource("client.xml");
String address = "https://localhost:" + PORT + "/services/";
- WebClient client = WebClient.create(address, setupProviders(), "alice", "security", busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "alice", "security", busFile.toString());
// Create the SAML Assertion
SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(true);
@@ -591,7 +604,8 @@ public class AuthorizationGrantNegativeTest extends AbstractBusClientServerTestB
URL busFile = AuthorizationGrantNegativeTest.class.getResource("client.xml");
String address = "https://localhost:" + PORT + "/services/";
- WebClient client = WebClient.create(address, setupProviders(), "alice", "security", busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "alice", "security", busFile.toString());
// Create the SAML Assertion
SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(true);
@@ -641,10 +655,11 @@ public class AuthorizationGrantNegativeTest extends AbstractBusClientServerTestB
URL busFile = AuthorizationGrantNegativeTest.class.getResource("client.xml");
String address = "https://localhost:" + PORT + "/services/";
- WebClient client = WebClient.create(address, setupProviders(), "alice", "security", busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "alice", "security", busFile.toString());
// Create the JWT Token
- String token = createToken("DoubleItSTSIssuer", "consumer-id",
+ String token = OAuth2TestUtils.createToken("DoubleItSTSIssuer", "consumer-id",
"https://localhost:" + PORT + "/services/token", true, false);
// Get Access Token
@@ -670,10 +685,11 @@ public class AuthorizationGrantNegativeTest extends AbstractBusClientServerTestB
URL busFile = AuthorizationGrantNegativeTest.class.getResource("client.xml");
String address = "https://localhost:" + PORT + "/services/";
- WebClient client = WebClient.create(address, setupProviders(), "alice", "security", busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "alice", "security", busFile.toString());
// Create the JWT Token
- String token = createToken(null, "consumer-id",
+ String token = OAuth2TestUtils.createToken(null, "consumer-id",
"https://localhost:" + PORT + "/services/token", true, true);
// Get Access Token
@@ -699,10 +715,11 @@ public class AuthorizationGrantNegativeTest extends AbstractBusClientServerTestB
URL busFile = AuthorizationGrantNegativeTest.class.getResource("client.xml");
String address = "https://localhost:" + PORT + "/services/";
- WebClient client = WebClient.create(address, setupProviders(), "alice", "security", busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "alice", "security", busFile.toString());
// Create the JWT Token
- String token = createToken("DoubleItSTSIssuer", "consumer-id",
+ String token = OAuth2TestUtils.createToken("DoubleItSTSIssuer", "consumer-id",
"https://localhost:" + PORT + "/services/token", false, true);
// Get Access Token
@@ -728,10 +745,11 @@ public class AuthorizationGrantNegativeTest extends AbstractBusClientServerTestB
URL busFile = AuthorizationGrantNegativeTest.class.getResource("client.xml");
String address = "https://localhost:" + PORT + "/services/";
- WebClient client = WebClient.create(address, setupProviders(), "alice", "security", busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "alice", "security", busFile.toString());
// Create the JWT Token
- String token = createToken("DoubleItSTSIssuer", "consumer-id",
+ String token = OAuth2TestUtils.createToken("DoubleItSTSIssuer", "consumer-id",
"https://localhost:" + PORT + "/services/badtoken", true, true);
// Get Access Token
@@ -757,7 +775,8 @@ public class AuthorizationGrantNegativeTest extends AbstractBusClientServerTestB
URL busFile = AuthorizationGrantNegativeTest.class.getResource("client.xml");
String address = "https://localhost:" + PORT + "/services/";
- WebClient client = WebClient.create(address, setupProviders(), "alice", "security", busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "alice", "security", busFile.toString());
// Create the JWT Token
// Create the JWT Token
@@ -807,143 +826,4 @@ public class AuthorizationGrantNegativeTest extends AbstractBusClientServerTestB
}
}
- private List<Object> setupProviders() {
- List<Object> providers = new ArrayList<Object>();
- JSONProvider<OAuthAuthorizationData> jsonP = new JSONProvider<OAuthAuthorizationData>();
- jsonP.setNamespaceMap(Collections.singletonMap("http://org.apache.cxf.rs.security.oauth",
- "ns2"));
- providers.add(jsonP);
- OAuthJSONProvider oauthProvider = new OAuthJSONProvider();
- providers.add(oauthProvider);
-
- return providers;
- }
-
- private String createToken(String audRestr, boolean saml2, boolean sign) throws WSSecurityException {
- SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(sign);
- samlCallbackHandler.setAudience(audRestr);
- if (!saml2) {
- samlCallbackHandler.setSaml2(false);
- samlCallbackHandler.setConfirmationMethod(SAML1Constants.CONF_BEARER);
- }
-
- SAMLCallback samlCallback = new SAMLCallback();
- SAMLUtil.doSAMLCallback(samlCallbackHandler, samlCallback);
-
- SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback);
- if (samlCallback.isSignAssertion()) {
- samlAssertion.signAssertion(
- samlCallback.getIssuerKeyName(),
- samlCallback.getIssuerKeyPassword(),
- samlCallback.getIssuerCrypto(),
- samlCallback.isSendKeyValue(),
- samlCallback.getCanonicalizationAlgorithm(),
- samlCallback.getSignatureAlgorithm()
- );
- }
-
- return samlAssertion.assertionToString();
- }
-
- private String createToken(String issuer, String subject, String audience,
- boolean expiry, boolean sign) {
- // Create the JWT Token
- JwtClaims claims = new JwtClaims();
- claims.setSubject(subject);
- if (issuer != null) {
- claims.setIssuer(issuer);
- }
- claims.setIssuedAt(new Date().getTime() / 1000L);
- if (expiry) {
- Calendar cal = Calendar.getInstance();
- cal.add(Calendar.SECOND, 60);
- claims.setExpiryTime(cal.getTimeInMillis() / 1000L);
- }
- if (audience != null) {
- claims.setAudiences(Collections.singletonList(audience));
- }
-
- if (sign) {
- // Sign the JWT Token
- Properties signingProperties = new Properties();
- signingProperties.put("rs.security.keystore.type", "jks");
- signingProperties.put("rs.security.keystore.password", "password");
- signingProperties.put("rs.security.keystore.alias", "alice");
- signingProperties.put("rs.security.keystore.file",
- "org/apache/cxf/systest/jaxrs/security/certs/alice.jks");
- signingProperties.put("rs.security.key.password", "password");
- signingProperties.put("rs.security.signature.algorithm", "RS256");
-
- JwsHeaders jwsHeaders = new JwsHeaders(signingProperties);
- JwsJwtCompactProducer jws = new JwsJwtCompactProducer(jwsHeaders, claims);
-
- JwsSignatureProvider sigProvider =
- JwsUtils.loadSignatureProvider(signingProperties, jwsHeaders);
-
- return jws.signWith(sigProvider);
- }
-
- JwsHeaders jwsHeaders = new JwsHeaders(SignatureAlgorithm.NONE);
- JwsJwtCompactProducer jws = new JwsJwtCompactProducer(jwsHeaders, claims);
- return jws.getSignedEncodedJws();
- }
-
- private String getAuthorizationCode(WebClient client) {
- return getAuthorizationCode(client, null);
- }
-
- private String getAuthorizationCode(WebClient client, String scope) {
- // Make initial authorization request
- client.type("application/json").accept("application/json");
- client.query("client_id", "consumer-id");
- client.query("redirect_uri", "http://www.blah.apache.org");
- client.query("response_type", "code");
- if (scope != null) {
- client.query("scope", scope);
- }
- client.path("authorize/");
- Response response = client.get();
-
- OAuthAuthorizationData authzData = response.readEntity(OAuthAuthorizationData.class);
-
- // Now call "decision" to get the authorization code grant
- client.path("decision");
- client.type("application/x-www-form-urlencoded");
-
- Form form = new Form();
- form.param("session_authenticity_token", authzData.getAuthenticityToken());
- form.param("client_id", authzData.getClientId());
- form.param("redirect_uri", authzData.getRedirectUri());
- if (authzData.getProposedScope() != null) {
- form.param("scope", authzData.getProposedScope());
- }
- form.param("oauthDecision", "allow");
-
- response = client.post(form);
- String location = response.getHeaderString("Location");
- return getSubstring(location, "code");
- }
-
- private ClientAccessToken getAccessTokenWithAuthorizationCode(WebClient client, String code) {
- client.type("application/x-www-form-urlencoded").accept("application/json");
- client.path("token");
-
- Form form = new Form();
- form.param("grant_type", "authorization_code");
- form.param("code", code);
- form.param("client_id", "consumer-id");
- Response response = client.post(form);
-
- return response.readEntity(ClientAccessToken.class);
- }
-
- private String getSubstring(String parentString, String substringName) {
- String foundString =
- parentString.substring(parentString.indexOf(substringName + "=") + (substringName + "=").length());
- int ampersandIndex = foundString.indexOf('&');
- if (ampersandIndex < 1) {
- ampersandIndex = foundString.length();
- }
- return foundString.substring(0, ampersandIndex);
- }
}
http://git-wip-us.apache.org/repos/asf/cxf/blob/2e8219cf/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/AuthorizationGrantTest.java
----------------------------------------------------------------------
diff --git a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/AuthorizationGrantTest.java b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/AuthorizationGrantTest.java
index ecdb2d2..3fe9a76 100644
--- a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/AuthorizationGrantTest.java
+++ b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/AuthorizationGrantTest.java
@@ -20,34 +20,16 @@
package org.apache.cxf.systest.jaxrs.security.oauth2.grants;
import java.net.URL;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Collections;
-import java.util.Date;
-import java.util.List;
-import java.util.Properties;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.Response;
import org.apache.cxf.common.util.Base64UrlUtility;
import org.apache.cxf.jaxrs.client.WebClient;
-import org.apache.cxf.jaxrs.provider.json.JSONProvider;
-import org.apache.cxf.rs.security.jose.jwa.SignatureAlgorithm;
-import org.apache.cxf.rs.security.jose.jws.JwsHeaders;
-import org.apache.cxf.rs.security.jose.jws.JwsJwtCompactProducer;
-import org.apache.cxf.rs.security.jose.jws.JwsSignatureProvider;
-import org.apache.cxf.rs.security.jose.jws.JwsUtils;
-import org.apache.cxf.rs.security.jose.jwt.JwtClaims;
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.systest.jaxrs.security.oauth2.SamlCallbackHandler;
+import org.apache.cxf.systest.jaxrs.security.oauth2.common.OAuth2TestUtils;
import org.apache.cxf.testutil.common.AbstractBusClientServerTestBase;
-import org.apache.wss4j.common.ext.WSSecurityException;
-import org.apache.wss4j.common.saml.SAMLCallback;
-import org.apache.wss4j.common.saml.SAMLUtil;
-import org.apache.wss4j.common.saml.SamlAssertionWrapper;
import org.junit.BeforeClass;
/**
@@ -67,22 +49,25 @@ public class AuthorizationGrantTest extends AbstractBusClientServerTestBase {
URL busFile = AuthorizationGrantTest.class.getResource("client.xml");
String address = "https://localhost:" + PORT + "/services/";
- WebClient client = WebClient.create(address, setupProviders(), "alice", "security", busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "alice", "security", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(client).getRequestContext().put(
org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
// Get Authorization Code
- String code = getAuthorizationCode(client);
+ String code = OAuth2TestUtils.getAuthorizationCode(client);
assertNotNull(code);
// Now get the access token
- client = WebClient.create(address, setupProviders(), "consumer-id", "this-is-a-secret", busFile.toString());
+ client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "consumer-id", "this-is-a-secret", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(client).getRequestContext().put(
org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
- ClientAccessToken accessToken = getAccessTokenWithAuthorizationCode(client, code);
+ ClientAccessToken accessToken =
+ OAuth2TestUtils.getAccessTokenWithAuthorizationCode(client, code);
assertNotNull(accessToken.getTokenKey());
}
@@ -91,22 +76,25 @@ public class AuthorizationGrantTest extends AbstractBusClientServerTestBase {
URL busFile = AuthorizationGrantTest.class.getResource("client.xml");
String address = "https://localhost:" + PORT + "/services/";
- WebClient client = WebClient.create(address, setupProviders(), "alice", "security", busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "alice", "security", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(client).getRequestContext().put(
org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
// Get Authorization Code
- String code = getAuthorizationCode(client);
+ String code = OAuth2TestUtils.getAuthorizationCode(client);
assertNotNull(code);
// Now get the access token
- client = WebClient.create(address, setupProviders(), "consumer-id", "this-is-a-secret", busFile.toString());
+ client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "consumer-id", "this-is-a-secret", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(client).getRequestContext().put(
org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
- ClientAccessToken accessToken = getAccessTokenWithAuthorizationCode(client, code);
+ ClientAccessToken accessToken =
+ OAuth2TestUtils.getAccessTokenWithAuthorizationCode(client, code);
assertNotNull(accessToken.getTokenKey());
assertNotNull(accessToken.getRefreshToken());
@@ -129,22 +117,25 @@ public class AuthorizationGrantTest extends AbstractBusClientServerTestBase {
URL busFile = AuthorizationGrantTest.class.getResource("client.xml");
String address = "https://localhost:" + PORT + "/services/";
- WebClient client = WebClient.create(address, setupProviders(), "alice", "security", busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "alice", "security", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(client).getRequestContext().put(
org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
// Get Authorization Code
- String code = getAuthorizationCode(client, "read_balance");
+ String code = OAuth2TestUtils.getAuthorizationCode(client, "read_balance");
assertNotNull(code);
// Now get the access token
- client = WebClient.create(address, setupProviders(), "consumer-id", "this-is-a-secret", busFile.toString());
+ client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "consumer-id", "this-is-a-secret", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(client).getRequestContext().put(
org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
- ClientAccessToken accessToken = getAccessTokenWithAuthorizationCode(client, code);
+ ClientAccessToken accessToken =
+ OAuth2TestUtils.getAccessTokenWithAuthorizationCode(client, code);
assertNotNull(accessToken.getTokenKey());
assertNotNull(accessToken.getRefreshToken());
@@ -168,22 +159,25 @@ public class AuthorizationGrantTest extends AbstractBusClientServerTestBase {
URL busFile = AuthorizationGrantTest.class.getResource("client.xml");
String address = "https://localhost:" + PORT + "/services/";
- WebClient client = WebClient.create(address, setupProviders(), "alice", "security", busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "alice", "security", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(client).getRequestContext().put(
org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
// Get Authorization Code
- String code = getAuthorizationCode(client, "read_balance");
+ String code = OAuth2TestUtils.getAuthorizationCode(client, "read_balance");
assertNotNull(code);
// Now get the access token
- client = WebClient.create(address, setupProviders(), "consumer-id", "this-is-a-secret", busFile.toString());
+ client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "consumer-id", "this-is-a-secret", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(client).getRequestContext().put(
org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
- ClientAccessToken accessToken = getAccessTokenWithAuthorizationCode(client, code);
+ ClientAccessToken accessToken =
+ OAuth2TestUtils.getAccessTokenWithAuthorizationCode(client, code);
assertNotNull(accessToken.getTokenKey());
}
@@ -192,7 +186,8 @@ public class AuthorizationGrantTest extends AbstractBusClientServerTestBase {
URL busFile = AuthorizationGrantTest.class.getResource("client.xml");
String address = "https://localhost:" + PORT + "/services/";
- WebClient client = WebClient.create(address, setupProviders(), "alice", "security", busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "alice", "security", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(client).getRequestContext().put(
org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
@@ -220,7 +215,7 @@ public class AuthorizationGrantTest extends AbstractBusClientServerTestBase {
response = client.post(form);
String location = response.getHeaderString("Location");
- String accessToken = getSubstring(location, "access_token");
+ String accessToken = OAuth2TestUtils.getSubstring(location, "access_token");
assertNotNull(accessToken);
}
@@ -229,8 +224,9 @@ public class AuthorizationGrantTest extends AbstractBusClientServerTestBase {
URL busFile = AuthorizationGrantTest.class.getResource("client.xml");
String address = "https://localhost:" + PORT + "/services/";
- WebClient client = WebClient.create(address, setupProviders(), "consumer-id",
- "this-is-a-secret", busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "consumer-id", "this-is-a-secret",
+ busFile.toString());
// Get Access Token
client.type("application/x-www-form-urlencoded").accept("application/json");
@@ -252,8 +248,9 @@ public class AuthorizationGrantTest extends AbstractBusClientServerTestBase {
URL busFile = AuthorizationGrantTest.class.getResource("client.xml");
String address = "https://localhost:" + PORT + "/services/";
- WebClient client = WebClient.create(address, setupProviders(), "consumer-id",
- "this-is-a-secret", busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "consumer-id", "this-is-a-secret",
+ busFile.toString());
// Get Access Token
client.type("application/x-www-form-urlencoded").accept("application/json");
@@ -273,10 +270,11 @@ public class AuthorizationGrantTest extends AbstractBusClientServerTestBase {
URL busFile = AuthorizationGrantTest.class.getResource("client.xml");
String address = "https://localhost:" + PORT + "/services/";
- WebClient client = WebClient.create(address, setupProviders(), "alice", "security", busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "alice", "security", busFile.toString());
// Create the SAML Assertion
- String assertion = createToken(address + "token");
+ String assertion = OAuth2TestUtils.createToken(address + "token");
// Get Access Token
client.type("application/x-www-form-urlencoded").accept("application/json");
@@ -298,10 +296,11 @@ public class AuthorizationGrantTest extends AbstractBusClientServerTestBase {
URL busFile = AuthorizationGrantTest.class.getResource("client.xml");
String address = "https://localhost:" + PORT + "/services/";
- WebClient client = WebClient.create(address, setupProviders(), "alice", "security", busFile.toString());
+ WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
+ "alice", "security", busFile.toString());
// Create the JWT Token
- String token = createToken("DoubleItSTSIssuer", "consumer-id",
+ String token = OAuth2TestUtils.createToken("DoubleItSTSIssuer", "consumer-id",
"https://localhost:" + PORT + "/services/token", true, true);
// Get Access Token
@@ -319,139 +318,4 @@ public class AuthorizationGrantTest extends AbstractBusClientServerTestBase {
assertNotNull(accessToken.getRefreshToken());
}
- private String getAuthorizationCode(WebClient client) {
- return getAuthorizationCode(client, null);
- }
-
- private String getAuthorizationCode(WebClient client, String scope) {
- // Make initial authorization request
- client.type("application/json").accept("application/json");
- client.query("client_id", "consumer-id");
- client.query("redirect_uri", "http://www.blah.apache.org");
- client.query("response_type", "code");
- if (scope != null) {
- client.query("scope", scope);
- }
- client.path("authorize/");
- Response response = client.get();
-
- OAuthAuthorizationData authzData = response.readEntity(OAuthAuthorizationData.class);
-
- // Now call "decision" to get the authorization code grant
- client.path("decision");
- client.type("application/x-www-form-urlencoded");
-
- Form form = new Form();
- form.param("session_authenticity_token", authzData.getAuthenticityToken());
- form.param("client_id", authzData.getClientId());
- form.param("redirect_uri", authzData.getRedirectUri());
- if (authzData.getProposedScope() != null) {
- form.param("scope", authzData.getProposedScope());
- }
- form.param("oauthDecision", "allow");
-
- response = client.post(form);
- String location = response.getHeaderString("Location");
- return getSubstring(location, "code");
- }
-
- private ClientAccessToken getAccessTokenWithAuthorizationCode(WebClient client, String code) {
- client.type("application/x-www-form-urlencoded").accept("application/json");
- client.path("token");
-
- Form form = new Form();
- form.param("grant_type", "authorization_code");
- form.param("code", code);
- form.param("client_id", "consumer-id");
- Response response = client.post(form);
-
- return response.readEntity(ClientAccessToken.class);
- }
-
- private List<Object> setupProviders() {
- List<Object> providers = new ArrayList<Object>();
- JSONProvider<OAuthAuthorizationData> jsonP = new JSONProvider<OAuthAuthorizationData>();
- jsonP.setNamespaceMap(Collections.singletonMap("http://org.apache.cxf.rs.security.oauth",
- "ns2"));
- providers.add(jsonP);
- OAuthJSONProvider oauthProvider = new OAuthJSONProvider();
- providers.add(oauthProvider);
-
- return providers;
- }
-
- private String createToken(String audRestr) throws WSSecurityException {
- SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(true);
- samlCallbackHandler.setAudience(audRestr);
-
- SAMLCallback samlCallback = new SAMLCallback();
- SAMLUtil.doSAMLCallback(samlCallbackHandler, samlCallback);
-
- SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback);
- if (samlCallback.isSignAssertion()) {
- samlAssertion.signAssertion(
- samlCallback.getIssuerKeyName(),
- samlCallback.getIssuerKeyPassword(),
- samlCallback.getIssuerCrypto(),
- samlCallback.isSendKeyValue(),
- samlCallback.getCanonicalizationAlgorithm(),
- samlCallback.getSignatureAlgorithm()
- );
- }
-
- return samlAssertion.assertionToString();
- }
-
- private String createToken(String issuer, String subject, String audience,
- boolean expiry, boolean sign) {
- // Create the JWT Token
- JwtClaims claims = new JwtClaims();
- claims.setSubject(subject);
- if (issuer != null) {
- claims.setIssuer(issuer);
- }
- claims.setIssuedAt(new Date().getTime() / 1000L);
- if (expiry) {
- Calendar cal = Calendar.getInstance();
- cal.add(Calendar.SECOND, 60);
- claims.setExpiryTime(cal.getTimeInMillis() / 1000L);
- }
- if (audience != null) {
- claims.setAudiences(Collections.singletonList(audience));
- }
-
- if (sign) {
- // Sign the JWT Token
- Properties signingProperties = new Properties();
- signingProperties.put("rs.security.keystore.type", "jks");
- signingProperties.put("rs.security.keystore.password", "password");
- signingProperties.put("rs.security.keystore.alias", "alice");
- signingProperties.put("rs.security.keystore.file",
- "org/apache/cxf/systest/jaxrs/security/certs/alice.jks");
- signingProperties.put("rs.security.key.password", "password");
- signingProperties.put("rs.security.signature.algorithm", "RS256");
-
- JwsHeaders jwsHeaders = new JwsHeaders(signingProperties);
- JwsJwtCompactProducer jws = new JwsJwtCompactProducer(jwsHeaders, claims);
-
- JwsSignatureProvider sigProvider =
- JwsUtils.loadSignatureProvider(signingProperties, jwsHeaders);
-
- return jws.signWith(sigProvider);
- }
-
- JwsHeaders jwsHeaders = new JwsHeaders(SignatureAlgorithm.NONE);
- JwsJwtCompactProducer jws = new JwsJwtCompactProducer(jwsHeaders, claims);
- return jws.getSignedEncodedJws();
- }
-
- private String getSubstring(String parentString, String substringName) {
- String foundString =
- parentString.substring(parentString.indexOf(substringName + "=") + (substringName + "=").length());
- int ampersandIndex = foundString.indexOf('&');
- if (ampersandIndex < 1) {
- ampersandIndex = foundString.length();
- }
- return foundString.substring(0, ampersandIndex);
- }
}
http://git-wip-us.apache.org/repos/asf/cxf/blob/2e8219cf/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/BasicAuthFilter.java
----------------------------------------------------------------------
diff --git a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/BasicAuthFilter.java b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/BasicAuthFilter.java
deleted file mode 100644
index db8fe4f..0000000
--- a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/BasicAuthFilter.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/**
- * 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.cxf.systest.jaxrs.security.oauth2.grants;
-
-import java.io.IOException;
-import java.security.Principal;
-
-import javax.security.auth.callback.CallbackHandler;
-import javax.ws.rs.container.ContainerRequestContext;
-import javax.ws.rs.container.ContainerRequestFilter;
-import javax.ws.rs.core.Response;
-
-import org.w3c.dom.Document;
-
-import org.apache.cxf.configuration.security.AuthorizationPolicy;
-import org.apache.cxf.helpers.DOMUtils;
-import org.apache.cxf.jaxrs.utils.ExceptionUtils;
-import org.apache.cxf.jaxrs.utils.JAXRSUtils;
-import org.apache.cxf.message.Message;
-import org.apache.cxf.security.SecurityContext;
-import org.apache.wss4j.common.principal.WSUsernameTokenPrincipalImpl;
-import org.apache.wss4j.dom.WSConstants;
-import org.apache.wss4j.dom.handler.RequestData;
-import org.apache.wss4j.dom.message.token.UsernameToken;
-import org.apache.wss4j.dom.validate.Credential;
-import org.apache.wss4j.dom.validate.UsernameTokenValidator;
-
-/**
- * A simple filter to validate a Basic Auth username/password via a CallbackHandler
- */
-public class BasicAuthFilter implements ContainerRequestFilter {
-
- private CallbackHandler callbackHandler;
-
- public void filter(ContainerRequestContext requestContext) throws IOException {
- Message message = JAXRSUtils.getCurrentMessage();
- AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);
-
- if (policy == null || policy.getUserName() == null || policy.getPassword() == null) {
- requestContext.abortWith(
- Response.status(401).header("WWW-Authenticate", "Basic realm=\"IdP\"").build());
- }
-
- try {
- UsernameToken token = convertPolicyToToken(policy);
- Credential credential = new Credential();
- credential.setUsernametoken(token);
-
- RequestData data = new RequestData();
- data.setMsgContext(message);
- data.setCallbackHandler(callbackHandler);
- UsernameTokenValidator validator = new UsernameTokenValidator();
- credential = validator.validate(credential, data);
-
- // Create a Principal/SecurityContext
- Principal p = null;
- if (credential != null && credential.getPrincipal() != null) {
- p = credential.getPrincipal();
- } else {
- p = new WSUsernameTokenPrincipalImpl(policy.getUserName(), false);
- ((WSUsernameTokenPrincipalImpl)p).setPassword(policy.getPassword());
- }
- message.put(SecurityContext.class, createSecurityContext(p));
- } catch (Exception ex) {
- throw ExceptionUtils.toInternalServerErrorException(ex, null);
- }
- }
-
- protected UsernameToken convertPolicyToToken(AuthorizationPolicy policy)
- throws Exception {
-
- Document doc = DOMUtils.createDocument();
- UsernameToken token = new UsernameToken(false, doc,
- WSConstants.PASSWORD_TEXT);
- token.setName(policy.getUserName());
- token.setPassword(policy.getPassword());
- return token;
- }
-
- protected SecurityContext createSecurityContext(final Principal p) {
- return new SecurityContext() {
-
- public Principal getUserPrincipal() {
- return p;
- }
-
- public boolean isUserInRole(String arg0) {
- return false;
- }
- };
- }
-
- public CallbackHandler getCallbackHandler() {
- return callbackHandler;
- }
-
- public void setCallbackHandler(CallbackHandler callbackHandler) {
- this.callbackHandler = callbackHandler;
- }
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cxf/blob/2e8219cf/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/BookServerOAuth2.java
----------------------------------------------------------------------
diff --git a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/BookServerOAuth2.java b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/BookServerOAuth2.java
new file mode 100644
index 0000000..88b7e33
--- /dev/null
+++ b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/BookServerOAuth2.java
@@ -0,0 +1,59 @@
+/**
+ * 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.cxf.systest.jaxrs.security.oauth2.grants;
+
+import java.net.URL;
+
+import org.apache.cxf.Bus;
+import org.apache.cxf.BusFactory;
+import org.apache.cxf.bus.spring.SpringBusFactory;
+import org.apache.cxf.testutil.common.AbstractBusTestServerBase;
+import org.apache.cxf.testutil.common.TestUtil;
+
+public class BookServerOAuth2 extends AbstractBusTestServerBase {
+ public static final String PORT = TestUtil.getPortNumber("jaxrs-oauth2");
+ private static final URL SERVER_CONFIG_FILE =
+ BookServerOAuth2.class.getResource("server.xml");
+
+ protected void run() {
+ SpringBusFactory bf = new SpringBusFactory();
+ Bus springBus = bf.createBus(SERVER_CONFIG_FILE);
+ BusFactory.setDefaultBus(springBus);
+ setBus(springBus);
+
+ try {
+ new BookServerOAuth2();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static void main(String[] args) {
+ try {
+ BookServerOAuth2 s = new BookServerOAuth2();
+ s.start();
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ System.exit(-1);
+ } finally {
+ System.out.println("done!");
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cxf/blob/2e8219cf/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/CallbackHandlerImpl.java
----------------------------------------------------------------------
diff --git a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/CallbackHandlerImpl.java b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/CallbackHandlerImpl.java
deleted file mode 100644
index 12c8658..0000000
--- a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/CallbackHandlerImpl.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/**
- * 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.cxf.systest.jaxrs.security.oauth2.grants;
-
-import java.io.IOException;
-
-import javax.security.auth.callback.Callback;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.callback.UnsupportedCallbackException;
-
-import org.apache.wss4j.common.ext.WSPasswordCallback;
-
-public class CallbackHandlerImpl implements CallbackHandler {
-
- public void handle(Callback[] callbacks) throws IOException,
- UnsupportedCallbackException {
- for (int i = 0; i < callbacks.length; i++) {
- if (callbacks[i] instanceof WSPasswordCallback) { // CXF
- WSPasswordCallback pc = (WSPasswordCallback) callbacks[i];
- if ("alice".equals(pc.getIdentifier())) {
- pc.setPassword("security");
- break;
- } else if ("bob".equals(pc.getIdentifier())) {
- pc.setPassword("security");
- break;
- } else if ("consumer-id".equals(pc.getIdentifier())) {
- pc.setPassword("this-is-a-secret");
- break;
- } else if ("service".equals(pc.getIdentifier())) {
- pc.setPassword("service-pass");
- break;
- }
- }
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cxf/blob/2e8219cf/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/CustomGrantHandler.java
----------------------------------------------------------------------
diff --git a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/CustomGrantHandler.java b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/CustomGrantHandler.java
new file mode 100644
index 0000000..7941452
--- /dev/null
+++ b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/grants/CustomGrantHandler.java
@@ -0,0 +1,51 @@
+/**
+ * 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.cxf.systest.jaxrs.security.oauth2.grants;
+
+import java.util.Collections;
+import java.util.List;
+
+import javax.ws.rs.core.MultivaluedMap;
+
+import org.apache.cxf.rs.security.oauth2.common.AccessTokenRegistration;
+import org.apache.cxf.rs.security.oauth2.common.Client;
+import org.apache.cxf.rs.security.oauth2.common.ServerAccessToken;
+import org.apache.cxf.rs.security.oauth2.provider.AccessTokenGrantHandler;
+import org.apache.cxf.rs.security.oauth2.provider.OAuthDataProvider;
+import org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException;
+
+public class CustomGrantHandler implements AccessTokenGrantHandler {
+
+ private OAuthDataProvider dataProvider;
+
+ public void setDataProvider(OAuthDataProvider dataProvider) {
+ this.dataProvider = dataProvider;
+ }
+
+ public List<String> getSupportedGrantTypes() {
+ return Collections.singletonList("custom_grant");
+ }
+
+ public ServerAccessToken createAccessToken(Client client, MultivaluedMap<String, String> params)
+ throws OAuthServiceException {
+ AccessTokenRegistration atr = new AccessTokenRegistration();
+ atr.setClient(client);
+ return dataProvider.createAccessToken(atr);
+ }
+}
[3/5] cxf git commit: Reshuffle of the tests to share some common code
Posted by co...@apache.org.
Reshuffle of the tests to share some common code
Project: http://git-wip-us.apache.org/repos/asf/cxf/repo
Commit: http://git-wip-us.apache.org/repos/asf/cxf/commit/2e8219cf
Tree: http://git-wip-us.apache.org/repos/asf/cxf/tree/2e8219cf
Diff: http://git-wip-us.apache.org/repos/asf/cxf/diff/2e8219cf
Branch: refs/heads/master
Commit: 2e8219cf3d047abc3a7e2611bf284aadbc20b7d6
Parents: 2fd41e1
Author: Colm O hEigeartaigh <co...@apache.org>
Authored: Wed Jan 20 15:00:26 2016 +0000
Committer: Colm O hEigeartaigh <co...@apache.org>
Committed: Wed Jan 20 15:00:59 2016 +0000
----------------------------------------------------------------------
.../jaxrs/security/oauth2/BookServerOAuth2.java | 59 --
.../security/oauth2/CustomGrantHandler.java | 51 --
.../jaxrs/security/oauth2/JAXRSOAuth2Test.java | 581 -------------------
.../security/oauth2/OAuthDataProviderImpl.java | 128 ----
.../security/oauth2/SamlCallbackHandler.java | 232 --------
.../security/oauth2/common/BasicAuthFilter.java | 117 ++++
.../oauth2/common/CallbackHandlerImpl.java | 52 ++
.../security/oauth2/common/OAuth2TestUtils.java | 201 +++++++
.../oauth2/common/OAuthDataProviderImpl.java | 161 +++++
.../oauth2/common/SamlCallbackHandler.java | 231 ++++++++
.../oauth2/filters/OAuth2FiltersTest.java | 169 ++----
.../oauth2/filters/OAuthDataProviderImpl.java | 97 ----
.../grants/AuthorizationGrantNegativeTest.java | 254 +++-----
.../oauth2/grants/AuthorizationGrantTest.java | 224 ++-----
.../security/oauth2/grants/BasicAuthFilter.java | 117 ----
.../oauth2/grants/BookServerOAuth2.java | 59 ++
.../oauth2/grants/CallbackHandlerImpl.java | 52 --
.../oauth2/grants/CustomGrantHandler.java | 51 ++
.../security/oauth2/grants/JAXRSOAuth2Test.java | 508 ++++++++++++++++
.../oauth2/grants/OAuthDataProviderImpl.java | 101 ----
.../systest/jaxrs/security/oauth2/client.xml | 38 --
.../security/oauth2/filters/oauth20-server.xml | 6 +-
.../oauth2/grants/grants-negative-server.xml | 6 +-
.../security/oauth2/grants/grants-server.xml | 6 +-
.../jaxrs/security/oauth2/grants/server.xml | 127 ++++
.../systest/jaxrs/security/oauth2/server.xml | 2 +-
26 files changed, 1681 insertions(+), 1949 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cxf/blob/2e8219cf/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/BookServerOAuth2.java
----------------------------------------------------------------------
diff --git a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/BookServerOAuth2.java b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/BookServerOAuth2.java
deleted file mode 100644
index a658e35..0000000
--- a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/BookServerOAuth2.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/**
- * 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.cxf.systest.jaxrs.security.oauth2;
-
-import java.net.URL;
-
-import org.apache.cxf.Bus;
-import org.apache.cxf.BusFactory;
-import org.apache.cxf.bus.spring.SpringBusFactory;
-import org.apache.cxf.testutil.common.AbstractBusTestServerBase;
-import org.apache.cxf.testutil.common.TestUtil;
-
-public class BookServerOAuth2 extends AbstractBusTestServerBase {
- public static final String PORT = TestUtil.getPortNumber("jaxrs-oauth2");
- private static final URL SERVER_CONFIG_FILE =
- BookServerOAuth2.class.getResource("server.xml");
-
- protected void run() {
- SpringBusFactory bf = new SpringBusFactory();
- Bus springBus = bf.createBus(SERVER_CONFIG_FILE);
- BusFactory.setDefaultBus(springBus);
- setBus(springBus);
-
- try {
- new BookServerOAuth2();
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- public static void main(String[] args) {
- try {
- BookServerOAuth2 s = new BookServerOAuth2();
- s.start();
- } catch (Exception ex) {
- ex.printStackTrace();
- System.exit(-1);
- } finally {
- System.out.println("done!");
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cxf/blob/2e8219cf/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/CustomGrantHandler.java
----------------------------------------------------------------------
diff --git a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/CustomGrantHandler.java b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/CustomGrantHandler.java
deleted file mode 100644
index 1d4b90a..0000000
--- a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/CustomGrantHandler.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/**
- * 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.cxf.systest.jaxrs.security.oauth2;
-
-import java.util.Collections;
-import java.util.List;
-
-import javax.ws.rs.core.MultivaluedMap;
-
-import org.apache.cxf.rs.security.oauth2.common.AccessTokenRegistration;
-import org.apache.cxf.rs.security.oauth2.common.Client;
-import org.apache.cxf.rs.security.oauth2.common.ServerAccessToken;
-import org.apache.cxf.rs.security.oauth2.provider.AccessTokenGrantHandler;
-import org.apache.cxf.rs.security.oauth2.provider.OAuthDataProvider;
-import org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException;
-
-public class CustomGrantHandler implements AccessTokenGrantHandler {
-
- private OAuthDataProvider dataProvider;
-
- public void setDataProvider(OAuthDataProvider dataProvider) {
- this.dataProvider = dataProvider;
- }
-
- public List<String> getSupportedGrantTypes() {
- return Collections.singletonList("custom_grant");
- }
-
- public ServerAccessToken createAccessToken(Client client, MultivaluedMap<String, String> params)
- throws OAuthServiceException {
- AccessTokenRegistration atr = new AccessTokenRegistration();
- atr.setClient(client);
- return dataProvider.createAccessToken(atr);
- }
-}
http://git-wip-us.apache.org/repos/asf/cxf/blob/2e8219cf/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/JAXRSOAuth2Test.java
----------------------------------------------------------------------
diff --git a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/JAXRSOAuth2Test.java b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/JAXRSOAuth2Test.java
deleted file mode 100644
index 97a24d1..0000000
--- a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/JAXRSOAuth2Test.java
+++ /dev/null
@@ -1,581 +0,0 @@
-/**
- * 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.cxf.systest.jaxrs.security.oauth2;
-
-import java.net.URL;
-import java.util.Calendar;
-import java.util.Collections;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.MultivaluedMap;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-import org.apache.cxf.Bus;
-import org.apache.cxf.bus.spring.SpringBusFactory;
-import org.apache.cxf.common.util.Base64UrlUtility;
-import org.apache.cxf.helpers.DOMUtils;
-import org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean;
-import org.apache.cxf.jaxrs.client.WebClient;
-import org.apache.cxf.jaxrs.impl.MetadataMap;
-import org.apache.cxf.rs.security.common.CryptoLoader;
-import org.apache.cxf.rs.security.jose.jwa.SignatureAlgorithm;
-import org.apache.cxf.rs.security.jose.jws.JwsHeaders;
-import org.apache.cxf.rs.security.jose.jws.JwsJwtCompactProducer;
-import org.apache.cxf.rs.security.jose.jws.JwsSignatureProvider;
-import org.apache.cxf.rs.security.jose.jws.JwsUtils;
-import org.apache.cxf.rs.security.jose.jwt.JwtClaims;
-import org.apache.cxf.rs.security.oauth2.auth.saml.Saml2BearerAuthOutInterceptor;
-import org.apache.cxf.rs.security.oauth2.client.Consumer;
-import org.apache.cxf.rs.security.oauth2.client.OAuthClientUtils;
-import org.apache.cxf.rs.security.oauth2.common.AccessTokenGrant;
-import org.apache.cxf.rs.security.oauth2.common.ClientAccessToken;
-import org.apache.cxf.rs.security.oauth2.grants.jwt.JwtBearerGrant;
-import org.apache.cxf.rs.security.oauth2.grants.saml.Saml2BearerGrant;
-import org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException;
-import org.apache.cxf.rs.security.oauth2.saml.Constants;
-import org.apache.cxf.rs.security.oauth2.utils.OAuthConstants;
-import org.apache.cxf.rs.security.saml.SAMLUtils;
-import org.apache.cxf.rs.security.saml.SAMLUtils.SelfSignInfo;
-import org.apache.cxf.testutil.common.AbstractBusClientServerTestBase;
-import org.apache.wss4j.common.crypto.Crypto;
-import org.apache.wss4j.common.ext.WSSecurityException;
-import org.apache.wss4j.common.saml.SAMLCallback;
-import org.apache.wss4j.common.saml.SAMLUtil;
-import org.apache.wss4j.common.saml.SamlAssertionWrapper;
-import org.apache.wss4j.common.saml.builder.SAML1Constants;
-import org.apache.wss4j.common.saml.builder.SAML2Constants;
-import org.apache.wss4j.common.util.DOM2Writer;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-public class JAXRSOAuth2Test extends AbstractBusClientServerTestBase {
- public static final String PORT = BookServerOAuth2.PORT;
- private static final String CRYPTO_RESOURCE_PROPERTIES =
- "org/apache/cxf/systest/jaxrs/security/alice.properties";
-
- @BeforeClass
- public static void startServers() throws Exception {
- assertTrue("server did not launch correctly",
- launchServer(BookServerOAuth2.class, true));
- }
-
- @Test
- public void testSAML2BearerGrant() throws Exception {
- String address = "https://localhost:" + PORT + "/oauth2/token";
- WebClient wc = createWebClient(address);
-
- Crypto crypto = new CryptoLoader().loadCrypto(CRYPTO_RESOURCE_PROPERTIES);
- SelfSignInfo signInfo = new SelfSignInfo(crypto, "alice", "password");
-
- SamlAssertionWrapper assertionWrapper = SAMLUtils.createAssertion(new SamlCallbackHandler(false),
- signInfo);
- Document doc = DOMUtils.newDocument();
- Element assertionElement = assertionWrapper.toDOM(doc);
- String assertion = DOM2Writer.nodeToString(assertionElement);
-
- Saml2BearerGrant grant = new Saml2BearerGrant(assertion);
- ClientAccessToken at = OAuthClientUtils.getAccessToken(wc,
- new Consumer("alice", "alice"),
- grant,
- false);
- assertNotNull(at.getTokenKey());
- }
-
- @Test
- public void testSAML2BearerAuthenticationDirect() throws Exception {
- String address = "https://localhost:" + PORT + "/oauth2-auth/token";
- WebClient wc = createWebClient(address);
-
- Crypto crypto = new CryptoLoader().loadCrypto(CRYPTO_RESOURCE_PROPERTIES);
- SelfSignInfo signInfo = new SelfSignInfo(crypto, "alice", "password");
-
- SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(true);
- samlCallbackHandler.setIssuer("alice");
- String audienceURI = "https://localhost:" + PORT + "/oauth2-auth/token";
- samlCallbackHandler.setAudience(audienceURI);
- SamlAssertionWrapper assertionWrapper = SAMLUtils.createAssertion(samlCallbackHandler,
- signInfo);
- Document doc = DOMUtils.newDocument();
- Element assertionElement = assertionWrapper.toDOM(doc);
- String assertion = DOM2Writer.nodeToString(assertionElement);
-
- String encodedAssertion = Base64UrlUtility.encode(assertion);
-
- Map<String, String> extraParams = new HashMap<String, String>();
- extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE, Constants.CLIENT_AUTH_SAML2_BEARER);
- extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, encodedAssertion);
-
- ClientAccessToken at = OAuthClientUtils.getAccessToken(wc,
- new CustomGrant(),
- extraParams);
- assertNotNull(at.getTokenKey());
- }
-
- @Test
- public void testTwoWayTLSAuthentication() throws Exception {
- String address = "https://localhost:" + PORT + "/oauth2/token";
- WebClient wc = createWebClient(address);
-
- ClientAccessToken at = OAuthClientUtils.getAccessToken(wc, new CustomGrant());
- assertNotNull(at.getTokenKey());
- }
-
- @Test
- public void testSAML2BearerAuthenticationInterceptor() throws Exception {
- String address = "https://localhost:" + PORT + "/oauth2-auth/token";
- WebClient wc = createWebClientWithProps(address);
-
- ClientAccessToken at = OAuthClientUtils.getAccessToken(wc,
- new CustomGrant());
- assertNotNull(at.getTokenKey());
- }
-
- @Test
- public void testJWTBearerGrant() throws Exception {
- String address = "https://localhost:" + PORT + "/oauth2/token";
- WebClient wc = createWebClient(address);
-
- // Create the JWT Token
- String token = createToken("resourceOwner", "alice", address, true, true);
-
- JwtBearerGrant grant = new JwtBearerGrant(token);
- ClientAccessToken at = OAuthClientUtils.getAccessToken(wc,
- new Consumer("alice", "alice"),
- grant,
- false);
- assertNotNull(at.getTokenKey());
- }
-
- @Test
- public void testJWTBearerAuthenticationDirect() throws Exception {
- String address = "https://localhost:" + PORT + "/oauth2-auth-jwt/token";
- WebClient wc = createWebClient(address);
-
- // Create the JWT Token
- String token = createToken("resourceOwner", "alice", address, true, true);
-
- Map<String, String> extraParams = new HashMap<String, String>();
- extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE,
- "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
- extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, token);
-
- ClientAccessToken at = OAuthClientUtils.getAccessToken(wc,
- new CustomGrant(),
- extraParams);
- assertNotNull(at.getTokenKey());
- }
-
- //
- // Some negative tests for authentication
- //
-
- @Test
- public void testSAML11() throws Exception {
- String address = "https://localhost:" + PORT + "/oauth2-auth/token";
- WebClient wc = createWebClient(address);
-
- String audienceURI = "https://localhost:" + PORT + "/oauth2-auth/token";
- String assertion = createToken(audienceURI, false, true);
- String encodedAssertion = Base64UrlUtility.encode(assertion);
-
- Map<String, String> extraParams = new HashMap<String, String>();
- extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE, Constants.CLIENT_AUTH_SAML2_BEARER);
- extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, encodedAssertion);
-
- try {
- OAuthClientUtils.getAccessToken(wc, new CustomGrant(), extraParams);
- fail("Failure expected on a SAML 1.1 Assertion");
- } catch (OAuthServiceException ex) {
- // expected
- }
- }
-
- @Test
- public void testSAMLAudRestr() throws Exception {
- String address = "https://localhost:" + PORT + "/oauth2-auth/token";
- WebClient wc = createWebClient(address);
-
- String audienceURI = "https://localhost:" + PORT + "/oauth2-auth/token2";
- String assertion = createToken(audienceURI, true, true);
- String encodedAssertion = Base64UrlUtility.encode(assertion);
-
- Map<String, String> extraParams = new HashMap<String, String>();
- extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE, Constants.CLIENT_AUTH_SAML2_BEARER);
- extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, encodedAssertion);
-
- try {
- OAuthClientUtils.getAccessToken(wc, new CustomGrant(), extraParams);
- fail("Failure expected on a bad audience restriction");
- } catch (OAuthServiceException ex) {
- // expected
- }
- }
-
- @Test
- public void testSAMLBadSubjectName() throws Exception {
- String address = "https://localhost:" + PORT + "/oauth2-auth/token";
- WebClient wc = createWebClient(address);
-
- String audienceURI = "https://localhost:" + PORT + "/oauth2-auth/token";
-
- // Create the SAML Assertion
- SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(true);
- samlCallbackHandler.setSubjectName("bob");
- samlCallbackHandler.setAudience(audienceURI);
-
- SAMLCallback samlCallback = new SAMLCallback();
- SAMLUtil.doSAMLCallback(samlCallbackHandler, samlCallback);
-
- SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback);
- if (samlCallback.isSignAssertion()) {
- samlAssertion.signAssertion(
- samlCallback.getIssuerKeyName(),
- samlCallback.getIssuerKeyPassword(),
- samlCallback.getIssuerCrypto(),
- samlCallback.isSendKeyValue(),
- samlCallback.getCanonicalizationAlgorithm(),
- samlCallback.getSignatureAlgorithm()
- );
- }
-
- String assertion = samlAssertion.assertionToString();
-
- String encodedAssertion = Base64UrlUtility.encode(assertion);
-
- Map<String, String> extraParams = new HashMap<String, String>();
- extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE, Constants.CLIENT_AUTH_SAML2_BEARER);
- extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, encodedAssertion);
-
- try {
- OAuthClientUtils.getAccessToken(wc, new CustomGrant(), extraParams);
- fail("Failure expected on a bad subject name");
- } catch (OAuthServiceException ex) {
- // expected
- }
- }
-
- @Test
- public void testSAMLUnsigned() throws Exception {
- String address = "https://localhost:" + PORT + "/oauth2-auth/token";
- WebClient wc = createWebClient(address);
-
- String audienceURI = "https://localhost:" + PORT + "/oauth2-auth/token";
- String assertion = createToken(audienceURI, true, false);
- String encodedAssertion = Base64UrlUtility.encode(assertion);
-
- Map<String, String> extraParams = new HashMap<String, String>();
- extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE, Constants.CLIENT_AUTH_SAML2_BEARER);
- extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, encodedAssertion);
-
- try {
- OAuthClientUtils.getAccessToken(wc, new CustomGrant(), extraParams);
- fail("Failure expected on an unsigned token");
- } catch (Exception ex) {
- // expected
- }
- }
-
- @Test
- public void testSAMLHolderOfKey() throws Exception {
- String address = "https://localhost:" + PORT + "/oauth2-auth/token";
- WebClient wc = createWebClient(address);
-
- String audienceURI = "https://localhost:" + PORT + "/oauth2-auth/token";
-
- // Create the SAML Assertion
- SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(true);
- samlCallbackHandler.setConfirmationMethod(SAML2Constants.CONF_HOLDER_KEY);
- samlCallbackHandler.setSubjectName("alice");
- samlCallbackHandler.setAudience(audienceURI);
-
- SAMLCallback samlCallback = new SAMLCallback();
- SAMLUtil.doSAMLCallback(samlCallbackHandler, samlCallback);
-
- SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback);
- if (samlCallback.isSignAssertion()) {
- samlAssertion.signAssertion(
- samlCallback.getIssuerKeyName(),
- samlCallback.getIssuerKeyPassword(),
- samlCallback.getIssuerCrypto(),
- samlCallback.isSendKeyValue(),
- samlCallback.getCanonicalizationAlgorithm(),
- samlCallback.getSignatureAlgorithm()
- );
- }
-
- String assertion = samlAssertion.assertionToString();
-
- String encodedAssertion = Base64UrlUtility.encode(assertion);
-
- Map<String, String> extraParams = new HashMap<String, String>();
- extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE, Constants.CLIENT_AUTH_SAML2_BEARER);
- extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, encodedAssertion);
-
- try {
- OAuthClientUtils.getAccessToken(wc, new CustomGrant(), extraParams);
- fail("Failure expected on a bad subject confirmation method");
- } catch (OAuthServiceException ex) {
- // expected
- }
- }
-
- @Test
- public void testJWTBadSubjectName() throws Exception {
- String address = "https://localhost:" + PORT + "/oauth2-auth-jwt/token";
- WebClient wc = createWebClient(address);
-
- // Create the JWT Token
- String token = createToken("resourceOwner", "bob", address, true, true);
-
- Map<String, String> extraParams = new HashMap<String, String>();
- extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE,
- "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
- extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, token);
-
- try {
- OAuthClientUtils.getAccessToken(wc, new CustomGrant(), extraParams);
- fail("Failure expected on a bad subject name");
- } catch (OAuthServiceException ex) {
- // expected
- }
- }
-
- @Test
- public void testJWTUnsigned() throws Exception {
- String address = "https://localhost:" + PORT + "/oauth2-auth-jwt/token";
- WebClient wc = createWebClient(address);
-
- // Create the JWT Token
- String token = createToken("resourceOwner", "alice", address, true, false);
-
- Map<String, String> extraParams = new HashMap<String, String>();
- extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE,
- "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
- extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, token);
-
- try {
- OAuthClientUtils.getAccessToken(wc, new CustomGrant(), extraParams);
- fail("Failure expected on an unsigned token");
- } catch (Exception ex) {
- // expected
- }
- }
-
- @Test
- public void testJWTNoIssuer() throws Exception {
- String address = "https://localhost:" + PORT + "/oauth2-auth-jwt/token";
- WebClient wc = createWebClient(address);
-
- // Create the JWT Token
- String token = createToken(null, "alice", address, true, true);
-
- Map<String, String> extraParams = new HashMap<String, String>();
- extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE,
- "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
- extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, token);
-
- try {
- OAuthClientUtils.getAccessToken(wc, new CustomGrant(), extraParams);
- fail("Failure expected on no issuer");
- } catch (Exception ex) {
- // expected
- }
- }
-
- @Test
- public void testJWTNoExpiry() throws Exception {
- String address = "https://localhost:" + PORT + "/oauth2-auth-jwt/token";
- WebClient wc = createWebClient(address);
-
- // Create the JWT Token
- String token = createToken("resourceOwner", "alice", address, false, true);
-
- Map<String, String> extraParams = new HashMap<String, String>();
- extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE,
- "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
- extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, token);
-
- try {
- OAuthClientUtils.getAccessToken(wc, new CustomGrant(), extraParams);
- fail("Failure expected on no expiry");
- } catch (Exception ex) {
- // expected
- }
- }
-
- @Test
- public void testJWTBadAudienceRestriction() throws Exception {
- String address = "https://localhost:" + PORT + "/oauth2-auth-jwt/token";
- WebClient wc = createWebClient(address);
-
- // Create the JWT Token
- String token = createToken("resourceOwner", "alice", address + "/badtoken", true, true);
-
- Map<String, String> extraParams = new HashMap<String, String>();
- extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE,
- "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
- extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, token);
-
- try {
- OAuthClientUtils.getAccessToken(wc, new CustomGrant(), extraParams);
- fail("Failure expected on a bad audience restriction");
- } catch (Exception ex) {
- // expected
- }
- }
-
- private WebClient createWebClient(String address) {
- JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean();
- bean.setAddress(address);
-
- SpringBusFactory bf = new SpringBusFactory();
- URL busFile = JAXRSOAuth2Test.class.getResource("client.xml");
- Bus springBus = bf.createBus(busFile.toString());
- bean.setBus(springBus);
-
- WebClient wc = bean.createWebClient();
- wc.type(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_JSON);
- return wc;
- }
-
- private WebClient createWebClientWithProps(String address) {
- JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean();
- bean.setAddress(address);
-
- SpringBusFactory bf = new SpringBusFactory();
- URL busFile = JAXRSOAuth2Test.class.getResource("client.xml");
- Bus springBus = bf.createBus(busFile.toString());
- bean.setBus(springBus);
-
- Map<String, Object> properties = new HashMap<String, Object>();
- properties.put("security.callback-handler",
- "org.apache.cxf.systest.jaxrs.security.saml.KeystorePasswordCallback");
-
- SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(true);
- samlCallbackHandler.setIssuer("alice");
- String audienceURI = "https://localhost:" + PORT + "/oauth2-auth/token";
- samlCallbackHandler.setAudience(audienceURI);
- properties.put("security.saml-callback-handler", samlCallbackHandler);
-
- properties.put("security.signature.username", "alice");
- properties.put("security.signature.properties", CRYPTO_RESOURCE_PROPERTIES);
- bean.setProperties(properties);
-
- bean.getOutInterceptors().add(new Saml2BearerAuthOutInterceptor());
-
- WebClient wc = bean.createWebClient();
- wc.type(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_JSON);
- return wc;
- }
-
- private String createToken(String audRestr, boolean saml2, boolean sign) throws WSSecurityException {
- SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(sign);
- samlCallbackHandler.setAudience(audRestr);
- if (!saml2) {
- samlCallbackHandler.setSaml2(false);
- samlCallbackHandler.setConfirmationMethod(SAML1Constants.CONF_BEARER);
- }
-
- SAMLCallback samlCallback = new SAMLCallback();
- SAMLUtil.doSAMLCallback(samlCallbackHandler, samlCallback);
-
- SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback);
- if (samlCallback.isSignAssertion()) {
- samlAssertion.signAssertion(
- samlCallback.getIssuerKeyName(),
- samlCallback.getIssuerKeyPassword(),
- samlCallback.getIssuerCrypto(),
- samlCallback.isSendKeyValue(),
- samlCallback.getCanonicalizationAlgorithm(),
- samlCallback.getSignatureAlgorithm()
- );
- }
-
- return samlAssertion.assertionToString();
- }
-
- private String createToken(String issuer, String subject, String audience,
- boolean expiry, boolean sign) {
- // Create the JWT Token
- JwtClaims claims = new JwtClaims();
- claims.setSubject(subject);
- if (issuer != null) {
- claims.setIssuer(issuer);
- }
- claims.setIssuedAt(new Date().getTime() / 1000L);
- if (expiry) {
- Calendar cal = Calendar.getInstance();
- cal.add(Calendar.SECOND, 60);
- claims.setExpiryTime(cal.getTimeInMillis() / 1000L);
- }
- if (audience != null) {
- claims.setAudiences(Collections.singletonList(audience));
- }
-
- if (sign) {
- // Sign the JWT Token
- Properties signingProperties = new Properties();
- signingProperties.put("rs.security.keystore.type", "jks");
- signingProperties.put("rs.security.keystore.password", "password");
- signingProperties.put("rs.security.keystore.alias", "alice");
- signingProperties.put("rs.security.keystore.file",
- "org/apache/cxf/systest/jaxrs/security/certs/alice.jks");
- signingProperties.put("rs.security.key.password", "password");
- signingProperties.put("rs.security.signature.algorithm", "RS256");
-
- JwsHeaders jwsHeaders = new JwsHeaders(signingProperties);
- JwsJwtCompactProducer jws = new JwsJwtCompactProducer(jwsHeaders, claims);
-
- JwsSignatureProvider sigProvider =
- JwsUtils.loadSignatureProvider(signingProperties, jwsHeaders);
-
- return jws.signWith(sigProvider);
- }
-
- JwsHeaders jwsHeaders = new JwsHeaders(SignatureAlgorithm.NONE);
- JwsJwtCompactProducer jws = new JwsJwtCompactProducer(jwsHeaders, claims);
- return jws.getSignedEncodedJws();
- }
-
- private static class CustomGrant implements AccessTokenGrant {
-
- private static final long serialVersionUID = -4007538779198315873L;
-
- @Override
- public String getType() {
- return "custom_grant";
- }
-
- @Override
- public MultivaluedMap<String, String> toMap() {
- MultivaluedMap<String, String> map = new MetadataMap<String, String>();
- map.putSingle(OAuthConstants.GRANT_TYPE, "custom_grant");
- return map;
- }
-
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cxf/blob/2e8219cf/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/OAuthDataProviderImpl.java
----------------------------------------------------------------------
diff --git a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/OAuthDataProviderImpl.java b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/OAuthDataProviderImpl.java
deleted file mode 100644
index cd3da5d..0000000
--- a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/OAuthDataProviderImpl.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/**
- * 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.cxf.systest.jaxrs.security.oauth2;
-
-import java.io.InputStream;
-import java.security.cert.Certificate;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.cxf.common.util.Base64Utility;
-import org.apache.cxf.rs.security.oauth2.common.AccessTokenRegistration;
-import org.apache.cxf.rs.security.oauth2.common.Client;
-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.provider.OAuthDataProvider;
-import org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException;
-import org.apache.cxf.rs.security.oauth2.saml.Constants;
-import org.apache.cxf.rs.security.oauth2.tokens.bearer.BearerAccessToken;
-import org.apache.cxf.rs.security.oauth2.tokens.refresh.RefreshToken;
-import org.apache.cxf.rt.security.crypto.CryptoUtils;
-
-
-public class OAuthDataProviderImpl implements OAuthDataProvider {
-
- private Map<String, Client> clients = new HashMap<String, Client>();
-
- public OAuthDataProviderImpl() throws Exception {
- Client client = new Client("alice", "alice", true);
- client.getAllowedGrantTypes().add(Constants.SAML2_BEARER_GRANT);
- client.getAllowedGrantTypes().add("urn:ietf:params:oauth:grant-type:jwt-bearer");
- client.getAllowedGrantTypes().add("custom_grant");
- clients.put(client.getClientId(), client);
-
-
- Certificate cert = loadCert();
- String encodedCert = Base64Utility.encode(cert.getEncoded());
-
- Client client2 = new Client("CN=whateverhost.com,OU=Morpit,O=ApacheTest,L=Syracuse,C=US",
- null,
- true,
- null,
- null);
- client2.getAllowedGrantTypes().add("custom_grant");
- client2.setApplicationCertificates(Collections.singletonList(encodedCert));
- clients.put(client2.getClientId(), client2);
- }
-
- private Certificate loadCert() throws Exception {
- InputStream is = this.getClass().getResourceAsStream("/org/apache/cxf/systest/http/resources/Truststore.jks");
- return CryptoUtils.loadCertificate(is, new char[]{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'}, "morpit", null);
- }
-
- @Override
- public Client getClient(String clientId) throws OAuthServiceException {
- return clients.get(clientId);
- }
-
- @Override
- public ServerAccessToken createAccessToken(AccessTokenRegistration accessToken)
- throws OAuthServiceException {
- return new BearerAccessToken(accessToken.getClient(), 3600);
- }
-
- @Override
- public ServerAccessToken getAccessToken(String accessToken) throws OAuthServiceException {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public ServerAccessToken getPreauthorizedToken(Client client, List<String> requestedScopes,
- UserSubject subject, String grantType)
- throws OAuthServiceException {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public ServerAccessToken refreshAccessToken(Client client, String refreshToken,
- List<String> requestedScopes) throws OAuthServiceException {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public List<OAuthPermission> convertScopeToPermissions(Client client, List<String> requestedScope) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public void revokeToken(Client client, String token, String tokenTypeHint) throws OAuthServiceException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public List<ServerAccessToken> getAccessTokens(Client client) throws OAuthServiceException {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public List<RefreshToken> getRefreshTokens(Client client) throws OAuthServiceException {
- // TODO Auto-generated method stub
- return null;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cxf/blob/2e8219cf/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/SamlCallbackHandler.java
----------------------------------------------------------------------
diff --git a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/SamlCallbackHandler.java b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/SamlCallbackHandler.java
deleted file mode 100644
index 8476974..0000000
--- a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/SamlCallbackHandler.java
+++ /dev/null
@@ -1,232 +0,0 @@
-/**
- * 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.cxf.systest.jaxrs.security.oauth2;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import javax.security.auth.callback.Callback;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.callback.UnsupportedCallbackException;
-
-import org.apache.cxf.helpers.CastUtils;
-import org.apache.cxf.message.Message;
-import org.apache.cxf.phase.PhaseInterceptorChain;
-import org.apache.cxf.rt.security.saml.claims.SAMLClaim;
-import org.apache.wss4j.common.crypto.Crypto;
-import org.apache.wss4j.common.crypto.CryptoFactory;
-import org.apache.wss4j.common.ext.WSSecurityException;
-import org.apache.wss4j.common.saml.SAMLCallback;
-import org.apache.wss4j.common.saml.bean.ActionBean;
-import org.apache.wss4j.common.saml.bean.AttributeBean;
-import org.apache.wss4j.common.saml.bean.AttributeStatementBean;
-import org.apache.wss4j.common.saml.bean.AudienceRestrictionBean;
-import org.apache.wss4j.common.saml.bean.AuthDecisionStatementBean;
-import org.apache.wss4j.common.saml.bean.AuthDecisionStatementBean.Decision;
-import org.apache.wss4j.common.saml.bean.AuthenticationStatementBean;
-import org.apache.wss4j.common.saml.bean.ConditionsBean;
-import org.apache.wss4j.common.saml.bean.SubjectBean;
-import org.apache.wss4j.common.saml.bean.Version;
-import org.apache.wss4j.common.saml.builder.SAML2Constants;
-import org.joda.time.DateTime;
-
-/**
- * A CallbackHandler instance that is used by the STS to mock up a SAML Attribute Assertion.
- */
-public class SamlCallbackHandler implements CallbackHandler {
- public static final String PORT = BookServerOAuth2.PORT;
- private String confirmationMethod = SAML2Constants.CONF_BEARER;
- private boolean signAssertion = true;
- private String issuer = "resourceOwner";
- private String audience = "https://localhost:" + PORT + "/oauth2/token";
- private boolean saml2 = true;
- private String cryptoPropertiesFile = "org/apache/cxf/systest/jaxrs/security/alice.properties";
- private String issuerKeyName = "alice";
- private String issuerKeyPassword = "password";
- private String subjectName = "alice";
-
- public SamlCallbackHandler(boolean signAssertion) {
- this.signAssertion = signAssertion;
- }
-
- public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
- Message m = PhaseInterceptorChain.getCurrentMessage();
-
- for (int i = 0; i < callbacks.length; i++) {
- if (callbacks[i] instanceof SAMLCallback) {
- SAMLCallback callback = (SAMLCallback) callbacks[i];
- if (saml2) {
- callback.setSamlVersion(Version.SAML_20);
- } else {
- callback.setSamlVersion(Version.SAML_11);
- }
- callback.setIssuer(issuer);
-
- String subject = m != null ? (String)m.getContextualProperty("saml.subject.name") : null;
- if (subject == null) {
- subject = subjectName;
- }
- String subjectQualifier = "www.mock-sts.com";
- SubjectBean subjectBean =
- new SubjectBean(
- subject, subjectQualifier, confirmationMethod
- );
- callback.setSubject(subjectBean);
-
- ConditionsBean conditions = new ConditionsBean();
-
- AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
- audienceRestriction.setAudienceURIs(Collections.singletonList(audience));
- conditions.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
-
- callback.setConditions(conditions);
-
- AuthDecisionStatementBean authDecBean = new AuthDecisionStatementBean();
- authDecBean.setDecision(Decision.INDETERMINATE);
- authDecBean.setResource("https://sp.example.com/SAML2");
- authDecBean.setSubject(subjectBean);
-
- ActionBean actionBean = new ActionBean();
- actionBean.setContents("Read");
- authDecBean.setActions(Collections.singletonList(actionBean));
- callback.setAuthDecisionStatementData(Collections.singletonList(authDecBean));
-
- AuthenticationStatementBean authBean = new AuthenticationStatementBean();
- authBean.setSubject(subjectBean);
- authBean.setAuthenticationInstant(new DateTime());
- authBean.setSessionIndex("123456");
- authBean.setSubject(subjectBean);
-
- // AuthnContextClassRef is not set
- authBean.setAuthenticationMethod(
- "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");
- callback.setAuthenticationStatementData(
- Collections.singletonList(authBean));
-
- AttributeStatementBean attrBean = new AttributeStatementBean();
- attrBean.setSubject(subjectBean);
-
- List<String> roles = m != null
- ? CastUtils.<String>cast((List<?>)m.getContextualProperty("saml.roles")) : null;
- if (roles == null) {
- roles = Collections.singletonList("user");
- }
- List<AttributeBean> claims = new ArrayList<AttributeBean>();
- AttributeBean roleClaim = new AttributeBean();
- roleClaim.setSimpleName("subject-role");
- roleClaim.setQualifiedName(SAMLClaim.SAML_ROLE_ATTRIBUTENAME_DEFAULT);
- roleClaim.setNameFormat(SAML2Constants.ATTRNAME_FORMAT_UNSPECIFIED);
- roleClaim.setAttributeValues(new ArrayList<Object>(roles));
- claims.add(roleClaim);
-
- List<String> authMethods =
- m != null ? CastUtils.<String>cast((List<?>)m.getContextualProperty("saml.auth")) : null;
- if (authMethods == null) {
- authMethods = Collections.singletonList("password");
- }
-
- AttributeBean authClaim = new AttributeBean();
- authClaim.setSimpleName("http://claims/authentication");
- authClaim.setQualifiedName("http://claims/authentication");
- authClaim.setNameFormat("http://claims/authentication-format");
- authClaim.setAttributeValues(new ArrayList<Object>(authMethods));
- claims.add(authClaim);
-
- attrBean.setSamlAttributes(claims);
- callback.setAttributeStatementData(Collections.singletonList(attrBean));
-
- if (signAssertion) {
- try {
- Crypto crypto = CryptoFactory.getInstance(cryptoPropertiesFile);
- callback.setIssuerCrypto(crypto);
- callback.setIssuerKeyName(issuerKeyName);
- callback.setIssuerKeyPassword(issuerKeyPassword);
- callback.setSignAssertion(true);
- } catch (WSSecurityException e) {
- throw new IOException(e);
- }
- }
- }
- }
- }
-
- public String getCryptoPropertiesFile() {
- return cryptoPropertiesFile;
- }
-
- public void setCryptoPropertiesFile(String cryptoPropertiesFile) {
- this.cryptoPropertiesFile = cryptoPropertiesFile;
- }
-
- public String getIssuerKeyName() {
- return issuerKeyName;
- }
-
- public void setIssuerKeyName(String issuerKeyName) {
- this.issuerKeyName = issuerKeyName;
- }
-
- public String getIssuerKeyPassword() {
- return issuerKeyPassword;
- }
-
- public void setIssuerKeyPassword(String issuerKeyPassword) {
- this.issuerKeyPassword = issuerKeyPassword;
- }
-
- public String getIssuer() {
- return issuer;
- }
-
- public void setIssuer(String issuer) {
- this.issuer = issuer;
- }
-
- public String getAudience() {
- return audience;
- }
-
- public void setAudience(String audience) {
- this.audience = audience;
- }
-
- public void setConfirmationMethod(String confMethod) {
- this.confirmationMethod = confMethod;
- }
-
- public boolean isSaml2() {
- return saml2;
- }
-
- public void setSaml2(boolean saml2) {
- this.saml2 = saml2;
- }
-
- public String getSubjectName() {
- return subjectName;
- }
-
- public void setSubjectName(String subjectName) {
- this.subjectName = subjectName;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cxf/blob/2e8219cf/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/common/BasicAuthFilter.java
----------------------------------------------------------------------
diff --git a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/common/BasicAuthFilter.java b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/common/BasicAuthFilter.java
new file mode 100644
index 0000000..1c74e6e
--- /dev/null
+++ b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/common/BasicAuthFilter.java
@@ -0,0 +1,117 @@
+/**
+ * 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.cxf.systest.jaxrs.security.oauth2.common;
+
+import java.io.IOException;
+import java.security.Principal;
+
+import javax.security.auth.callback.CallbackHandler;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.container.ContainerRequestFilter;
+import javax.ws.rs.core.Response;
+
+import org.w3c.dom.Document;
+
+import org.apache.cxf.configuration.security.AuthorizationPolicy;
+import org.apache.cxf.helpers.DOMUtils;
+import org.apache.cxf.jaxrs.utils.ExceptionUtils;
+import org.apache.cxf.jaxrs.utils.JAXRSUtils;
+import org.apache.cxf.message.Message;
+import org.apache.cxf.security.SecurityContext;
+import org.apache.wss4j.common.principal.WSUsernameTokenPrincipalImpl;
+import org.apache.wss4j.dom.WSConstants;
+import org.apache.wss4j.dom.handler.RequestData;
+import org.apache.wss4j.dom.message.token.UsernameToken;
+import org.apache.wss4j.dom.validate.Credential;
+import org.apache.wss4j.dom.validate.UsernameTokenValidator;
+
+/**
+ * A simple filter to validate a Basic Auth username/password via a CallbackHandler
+ */
+public class BasicAuthFilter implements ContainerRequestFilter {
+
+ private CallbackHandler callbackHandler;
+
+ public void filter(ContainerRequestContext requestContext) throws IOException {
+ Message message = JAXRSUtils.getCurrentMessage();
+ AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);
+
+ if (policy == null || policy.getUserName() == null || policy.getPassword() == null) {
+ requestContext.abortWith(
+ Response.status(401).header("WWW-Authenticate", "Basic realm=\"IdP\"").build());
+ }
+
+ try {
+ UsernameToken token = convertPolicyToToken(policy);
+ Credential credential = new Credential();
+ credential.setUsernametoken(token);
+
+ RequestData data = new RequestData();
+ data.setMsgContext(message);
+ data.setCallbackHandler(callbackHandler);
+ UsernameTokenValidator validator = new UsernameTokenValidator();
+ credential = validator.validate(credential, data);
+
+ // Create a Principal/SecurityContext
+ Principal p = null;
+ if (credential != null && credential.getPrincipal() != null) {
+ p = credential.getPrincipal();
+ } else {
+ p = new WSUsernameTokenPrincipalImpl(policy.getUserName(), false);
+ ((WSUsernameTokenPrincipalImpl)p).setPassword(policy.getPassword());
+ }
+ message.put(SecurityContext.class, createSecurityContext(p));
+ } catch (Exception ex) {
+ throw ExceptionUtils.toInternalServerErrorException(ex, null);
+ }
+ }
+
+ protected UsernameToken convertPolicyToToken(AuthorizationPolicy policy)
+ throws Exception {
+
+ Document doc = DOMUtils.createDocument();
+ UsernameToken token = new UsernameToken(false, doc,
+ WSConstants.PASSWORD_TEXT);
+ token.setName(policy.getUserName());
+ token.setPassword(policy.getPassword());
+ return token;
+ }
+
+ protected SecurityContext createSecurityContext(final Principal p) {
+ return new SecurityContext() {
+
+ public Principal getUserPrincipal() {
+ return p;
+ }
+
+ public boolean isUserInRole(String arg0) {
+ return false;
+ }
+ };
+ }
+
+ public CallbackHandler getCallbackHandler() {
+ return callbackHandler;
+ }
+
+ public void setCallbackHandler(CallbackHandler callbackHandler) {
+ this.callbackHandler = callbackHandler;
+ }
+
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cxf/blob/2e8219cf/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/common/CallbackHandlerImpl.java
----------------------------------------------------------------------
diff --git a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/common/CallbackHandlerImpl.java b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/common/CallbackHandlerImpl.java
new file mode 100644
index 0000000..159740c
--- /dev/null
+++ b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/common/CallbackHandlerImpl.java
@@ -0,0 +1,52 @@
+/**
+ * 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.cxf.systest.jaxrs.security.oauth2.common;
+
+import java.io.IOException;
+
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.UnsupportedCallbackException;
+
+import org.apache.wss4j.common.ext.WSPasswordCallback;
+
+public class CallbackHandlerImpl implements CallbackHandler {
+
+ public void handle(Callback[] callbacks) throws IOException,
+ UnsupportedCallbackException {
+ for (int i = 0; i < callbacks.length; i++) {
+ if (callbacks[i] instanceof WSPasswordCallback) { // CXF
+ WSPasswordCallback pc = (WSPasswordCallback) callbacks[i];
+ if ("alice".equals(pc.getIdentifier())) {
+ pc.setPassword("security");
+ break;
+ } else if ("bob".equals(pc.getIdentifier())) {
+ pc.setPassword("security");
+ break;
+ } else if ("consumer-id".equals(pc.getIdentifier())) {
+ pc.setPassword("this-is-a-secret");
+ break;
+ } else if ("service".equals(pc.getIdentifier())) {
+ pc.setPassword("service-pass");
+ break;
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cxf/blob/2e8219cf/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/common/OAuth2TestUtils.java
----------------------------------------------------------------------
diff --git a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/common/OAuth2TestUtils.java b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/common/OAuth2TestUtils.java
new file mode 100644
index 0000000..8982ee0
--- /dev/null
+++ b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/common/OAuth2TestUtils.java
@@ -0,0 +1,201 @@
+/**
+ * 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.cxf.systest.jaxrs.security.oauth2.common;
+
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Collections;
+import java.util.Date;
+import java.util.List;
+import java.util.Properties;
+
+import javax.ws.rs.core.Form;
+import javax.ws.rs.core.Response;
+
+import org.apache.cxf.jaxrs.client.WebClient;
+import org.apache.cxf.jaxrs.provider.json.JSONProvider;
+import org.apache.cxf.rs.security.jose.jwa.SignatureAlgorithm;
+import org.apache.cxf.rs.security.jose.jws.JwsHeaders;
+import org.apache.cxf.rs.security.jose.jws.JwsJwtCompactProducer;
+import org.apache.cxf.rs.security.jose.jws.JwsSignatureProvider;
+import org.apache.cxf.rs.security.jose.jws.JwsUtils;
+import org.apache.cxf.rs.security.jose.jwt.JwtClaims;
+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.wss4j.common.ext.WSSecurityException;
+import org.apache.wss4j.common.saml.SAMLCallback;
+import org.apache.wss4j.common.saml.SAMLUtil;
+import org.apache.wss4j.common.saml.SamlAssertionWrapper;
+import org.apache.wss4j.common.saml.builder.SAML1Constants;
+
+/**
+ * Some test utils for the OAuth 2.0 tests
+ */
+public final class OAuth2TestUtils {
+
+ private OAuth2TestUtils() {
+ // complete
+ }
+
+ public static String getAuthorizationCode(WebClient client) {
+ return getAuthorizationCode(client, null);
+ }
+
+ public static String getAuthorizationCode(WebClient client, String scope) {
+ // Make initial authorization request
+ client.type("application/json").accept("application/json");
+ client.query("client_id", "consumer-id");
+ client.query("redirect_uri", "http://www.blah.apache.org");
+ client.query("response_type", "code");
+ if (scope != null) {
+ client.query("scope", scope);
+ }
+ client.path("authorize/");
+ Response response = client.get();
+
+ OAuthAuthorizationData authzData = response.readEntity(OAuthAuthorizationData.class);
+
+ // Now call "decision" to get the authorization code grant
+ client.path("decision");
+ client.type("application/x-www-form-urlencoded");
+
+ Form form = new Form();
+ form.param("session_authenticity_token", authzData.getAuthenticityToken());
+ form.param("client_id", authzData.getClientId());
+ form.param("redirect_uri", authzData.getRedirectUri());
+ if (authzData.getProposedScope() != null) {
+ form.param("scope", authzData.getProposedScope());
+ }
+ form.param("oauthDecision", "allow");
+
+ response = client.post(form);
+ String location = response.getHeaderString("Location");
+ return getSubstring(location, "code");
+ }
+
+ public static ClientAccessToken getAccessTokenWithAuthorizationCode(WebClient client, String code) {
+ client.type("application/x-www-form-urlencoded").accept("application/json");
+ client.path("token");
+
+ Form form = new Form();
+ form.param("grant_type", "authorization_code");
+ form.param("code", code);
+ form.param("client_id", "consumer-id");
+ Response response = client.post(form);
+
+ return response.readEntity(ClientAccessToken.class);
+ }
+
+ public static List<Object> setupProviders() {
+ List<Object> providers = new ArrayList<Object>();
+ JSONProvider<OAuthAuthorizationData> jsonP = new JSONProvider<OAuthAuthorizationData>();
+ jsonP.setNamespaceMap(Collections.singletonMap("http://org.apache.cxf.rs.security.oauth",
+ "ns2"));
+ providers.add(jsonP);
+ OAuthJSONProvider oauthProvider = new OAuthJSONProvider();
+ providers.add(oauthProvider);
+
+ return providers;
+ }
+
+ public static String createToken(String audRestr) throws WSSecurityException {
+ return createToken(audRestr, true, true);
+ }
+
+ public static String createToken(String audRestr, boolean saml2, boolean sign)
+ throws WSSecurityException {
+ SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(sign);
+ samlCallbackHandler.setAudience(audRestr);
+ if (!saml2) {
+ samlCallbackHandler.setSaml2(false);
+ samlCallbackHandler.setConfirmationMethod(SAML1Constants.CONF_BEARER);
+ }
+
+ SAMLCallback samlCallback = new SAMLCallback();
+ SAMLUtil.doSAMLCallback(samlCallbackHandler, samlCallback);
+
+ SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback);
+ if (samlCallback.isSignAssertion()) {
+ samlAssertion.signAssertion(
+ samlCallback.getIssuerKeyName(),
+ samlCallback.getIssuerKeyPassword(),
+ samlCallback.getIssuerCrypto(),
+ samlCallback.isSendKeyValue(),
+ samlCallback.getCanonicalizationAlgorithm(),
+ samlCallback.getSignatureAlgorithm()
+ );
+ }
+
+ return samlAssertion.assertionToString();
+ }
+
+ public static String createToken(String issuer, String subject, String audience,
+ boolean expiry, boolean sign) {
+ // Create the JWT Token
+ JwtClaims claims = new JwtClaims();
+ claims.setSubject(subject);
+ if (issuer != null) {
+ claims.setIssuer(issuer);
+ }
+ claims.setIssuedAt(new Date().getTime() / 1000L);
+ if (expiry) {
+ Calendar cal = Calendar.getInstance();
+ cal.add(Calendar.SECOND, 60);
+ claims.setExpiryTime(cal.getTimeInMillis() / 1000L);
+ }
+ if (audience != null) {
+ claims.setAudiences(Collections.singletonList(audience));
+ }
+
+ if (sign) {
+ // Sign the JWT Token
+ Properties signingProperties = new Properties();
+ signingProperties.put("rs.security.keystore.type", "jks");
+ signingProperties.put("rs.security.keystore.password", "password");
+ signingProperties.put("rs.security.keystore.alias", "alice");
+ signingProperties.put("rs.security.keystore.file",
+ "org/apache/cxf/systest/jaxrs/security/certs/alice.jks");
+ signingProperties.put("rs.security.key.password", "password");
+ signingProperties.put("rs.security.signature.algorithm", "RS256");
+
+ JwsHeaders jwsHeaders = new JwsHeaders(signingProperties);
+ JwsJwtCompactProducer jws = new JwsJwtCompactProducer(jwsHeaders, claims);
+
+ JwsSignatureProvider sigProvider =
+ JwsUtils.loadSignatureProvider(signingProperties, jwsHeaders);
+
+ return jws.signWith(sigProvider);
+ }
+
+ JwsHeaders jwsHeaders = new JwsHeaders(SignatureAlgorithm.NONE);
+ JwsJwtCompactProducer jws = new JwsJwtCompactProducer(jwsHeaders, claims);
+ return jws.getSignedEncodedJws();
+ }
+
+ public static String getSubstring(String parentString, String substringName) {
+ String foundString =
+ parentString.substring(parentString.indexOf(substringName + "=") + (substringName + "=").length());
+ int ampersandIndex = foundString.indexOf('&');
+ if (ampersandIndex < 1) {
+ ampersandIndex = foundString.length();
+ }
+ return foundString.substring(0, ampersandIndex);
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cxf/blob/2e8219cf/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/common/OAuthDataProviderImpl.java
----------------------------------------------------------------------
diff --git a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/common/OAuthDataProviderImpl.java b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/common/OAuthDataProviderImpl.java
new file mode 100644
index 0000000..ae1b9db
--- /dev/null
+++ b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/common/OAuthDataProviderImpl.java
@@ -0,0 +1,161 @@
+/**
+ * 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.cxf.systest.jaxrs.security.oauth2.common;
+
+import java.io.InputStream;
+import java.security.cert.Certificate;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import org.apache.cxf.common.util.Base64Utility;
+import org.apache.cxf.rs.security.oauth2.common.Client;
+import org.apache.cxf.rs.security.oauth2.common.OAuthPermission;
+import org.apache.cxf.rs.security.oauth2.grants.code.DefaultEHCacheCodeDataProvider;
+import org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException;
+import org.apache.cxf.rs.security.oauth2.saml.Constants;
+import org.apache.cxf.rt.security.crypto.CryptoUtils;
+
+/**
+ * Extend the DefaultEHCacheCodeDataProvider to allow refreshing of tokens
+ */
+public class OAuthDataProviderImpl extends DefaultEHCacheCodeDataProvider {
+
+ public OAuthDataProviderImpl() throws Exception {
+ // filters/grants test client
+ Client client = new Client("consumer-id", "this-is-a-secret", true);
+ client.setRedirectUris(Collections.singletonList("http://www.blah.apache.org"));
+
+ client.getAllowedGrantTypes().add("authorization_code");
+ client.getAllowedGrantTypes().add("refresh_token");
+ client.getAllowedGrantTypes().add("implicit");
+ client.getAllowedGrantTypes().add("password");
+ client.getAllowedGrantTypes().add("client_credentials");
+ client.getAllowedGrantTypes().add("urn:ietf:params:oauth:grant-type:saml2-bearer");
+ client.getAllowedGrantTypes().add("urn:ietf:params:oauth:grant-type:jwt-bearer");
+
+ client.getRegisteredScopes().add("read_balance");
+ client.getRegisteredScopes().add("create_balance");
+ client.getRegisteredScopes().add("read_data");
+ client.getRegisteredScopes().add("read_book");
+ client.getRegisteredScopes().add("create_book");
+ client.getRegisteredScopes().add("create_image");
+
+ this.setClient(client);
+
+ // JAXRSOAuth2Test clients
+ client = new Client("alice", "alice", true);
+ client.getAllowedGrantTypes().add(Constants.SAML2_BEARER_GRANT);
+ client.getAllowedGrantTypes().add("urn:ietf:params:oauth:grant-type:jwt-bearer");
+ client.getAllowedGrantTypes().add("custom_grant");
+ this.setClient(client);
+
+ Certificate cert = loadCert();
+ String encodedCert = Base64Utility.encode(cert.getEncoded());
+
+ Client client2 = new Client("CN=whateverhost.com,OU=Morpit,O=ApacheTest,L=Syracuse,C=US",
+ null,
+ true,
+ null,
+ null);
+ client2.getAllowedGrantTypes().add("custom_grant");
+ client2.setApplicationCertificates(Collections.singletonList(encodedCert));
+ this.setClient(client2);
+ }
+
+ private Certificate loadCert() throws Exception {
+ InputStream is = this.getClass().getResourceAsStream("/org/apache/cxf/systest/http/resources/Truststore.jks");
+ return CryptoUtils.loadCertificate(is, new char[]{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'}, "morpit", null);
+ }
+
+ @Override
+ protected boolean isRefreshTokenSupported(List<String> theScopes) {
+ return true;
+ }
+
+ @Override
+ public List<OAuthPermission> convertScopeToPermissions(Client client, List<String> requestedScopes) {
+ if (requestedScopes.isEmpty()) {
+ return Collections.emptyList();
+ }
+
+ List<OAuthPermission> permissions = new ArrayList<>();
+ for (String requestedScope : requestedScopes) {
+ if ("read_book".equals(requestedScope)) {
+ OAuthPermission permission = new OAuthPermission();
+ permission.setHttpVerbs(Collections.singletonList("GET"));
+ List<String> uris = new ArrayList<>();
+ String partnerAddress = "/secured/bookstore/books/*";
+ uris.add(partnerAddress);
+ permission.setUris(uris);
+
+ permissions.add(permission);
+ } else if ("create_book".equals(requestedScope)) {
+ OAuthPermission permission = new OAuthPermission();
+ permission.setHttpVerbs(Collections.singletonList("POST"));
+ List<String> uris = new ArrayList<>();
+ String partnerAddress = "/secured/bookstore/books/*";
+ uris.add(partnerAddress);
+ permission.setUris(uris);
+
+ permissions.add(permission);
+ } else if ("create_image".equals(requestedScope)) {
+ OAuthPermission permission = new OAuthPermission();
+ permission.setHttpVerbs(Collections.singletonList("POST"));
+ List<String> uris = new ArrayList<>();
+ String partnerAddress = "/secured/bookstore/image/*";
+ uris.add(partnerAddress);
+ permission.setUris(uris);
+
+ permissions.add(permission);
+ } else if ("read_balance".equals(requestedScope)) {
+ OAuthPermission permission = new OAuthPermission();
+ permission.setHttpVerbs(Collections.singletonList("GET"));
+ List<String> uris = new ArrayList<>();
+ String partnerAddress = "/partners/balance/*";
+ uris.add(partnerAddress);
+ permission.setUris(uris);
+
+ permissions.add(permission);
+ } else if ("create_balance".equals(requestedScope)) {
+ OAuthPermission permission = new OAuthPermission();
+ permission.setHttpVerbs(Collections.singletonList("POST"));
+ List<String> uris = new ArrayList<>();
+ String partnerAddress = "/partners/balance/*";
+ uris.add(partnerAddress);
+ permission.setUris(uris);
+
+ permissions.add(permission);
+ } else if ("read_data".equals(requestedScope)) {
+ OAuthPermission permission = new OAuthPermission();
+ permission.setHttpVerbs(Collections.singletonList("GET"));
+ List<String> uris = new ArrayList<>();
+ String partnerAddress = "/partners/data/*";
+ uris.add(partnerAddress);
+ permission.setUris(uris);
+
+ permissions.add(permission);
+ } else {
+ throw new OAuthServiceException("invalid_scope");
+ }
+ }
+
+ return permissions;
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cxf/blob/2e8219cf/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/common/SamlCallbackHandler.java
----------------------------------------------------------------------
diff --git a/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/common/SamlCallbackHandler.java b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/common/SamlCallbackHandler.java
new file mode 100644
index 0000000..1a92f42
--- /dev/null
+++ b/systests/rs-security/src/test/java/org/apache/cxf/systest/jaxrs/security/oauth2/common/SamlCallbackHandler.java
@@ -0,0 +1,231 @@
+/**
+ * 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.cxf.systest.jaxrs.security.oauth2.common;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.UnsupportedCallbackException;
+
+import org.apache.cxf.helpers.CastUtils;
+import org.apache.cxf.message.Message;
+import org.apache.cxf.phase.PhaseInterceptorChain;
+import org.apache.cxf.rt.security.saml.claims.SAMLClaim;
+import org.apache.wss4j.common.crypto.Crypto;
+import org.apache.wss4j.common.crypto.CryptoFactory;
+import org.apache.wss4j.common.ext.WSSecurityException;
+import org.apache.wss4j.common.saml.SAMLCallback;
+import org.apache.wss4j.common.saml.bean.ActionBean;
+import org.apache.wss4j.common.saml.bean.AttributeBean;
+import org.apache.wss4j.common.saml.bean.AttributeStatementBean;
+import org.apache.wss4j.common.saml.bean.AudienceRestrictionBean;
+import org.apache.wss4j.common.saml.bean.AuthDecisionStatementBean;
+import org.apache.wss4j.common.saml.bean.AuthDecisionStatementBean.Decision;
+import org.apache.wss4j.common.saml.bean.AuthenticationStatementBean;
+import org.apache.wss4j.common.saml.bean.ConditionsBean;
+import org.apache.wss4j.common.saml.bean.SubjectBean;
+import org.apache.wss4j.common.saml.bean.Version;
+import org.apache.wss4j.common.saml.builder.SAML2Constants;
+import org.joda.time.DateTime;
+
+/**
+ * A CallbackHandler instance that is used by the STS to mock up a SAML Attribute Assertion.
+ */
+public class SamlCallbackHandler implements CallbackHandler {
+ private String confirmationMethod = SAML2Constants.CONF_BEARER;
+ private boolean signAssertion = true;
+ private String issuer = "resourceOwner";
+ private String audience;
+ private boolean saml2 = true;
+ private String cryptoPropertiesFile = "org/apache/cxf/systest/jaxrs/security/alice.properties";
+ private String issuerKeyName = "alice";
+ private String issuerKeyPassword = "password";
+ private String subjectName = "alice";
+
+ public SamlCallbackHandler(boolean signAssertion) {
+ this.signAssertion = signAssertion;
+ }
+
+ public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
+ Message m = PhaseInterceptorChain.getCurrentMessage();
+
+ for (int i = 0; i < callbacks.length; i++) {
+ if (callbacks[i] instanceof SAMLCallback) {
+ SAMLCallback callback = (SAMLCallback) callbacks[i];
+ if (saml2) {
+ callback.setSamlVersion(Version.SAML_20);
+ } else {
+ callback.setSamlVersion(Version.SAML_11);
+ }
+ callback.setIssuer(issuer);
+
+ String subject = m != null ? (String)m.getContextualProperty("saml.subject.name") : null;
+ if (subject == null) {
+ subject = subjectName;
+ }
+ String subjectQualifier = "www.mock-sts.com";
+ SubjectBean subjectBean =
+ new SubjectBean(
+ subject, subjectQualifier, confirmationMethod
+ );
+ callback.setSubject(subjectBean);
+
+ ConditionsBean conditions = new ConditionsBean();
+
+ AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
+ audienceRestriction.setAudienceURIs(Collections.singletonList(audience));
+ conditions.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
+
+ callback.setConditions(conditions);
+
+ AuthDecisionStatementBean authDecBean = new AuthDecisionStatementBean();
+ authDecBean.setDecision(Decision.INDETERMINATE);
+ authDecBean.setResource("https://sp.example.com/SAML2");
+ authDecBean.setSubject(subjectBean);
+
+ ActionBean actionBean = new ActionBean();
+ actionBean.setContents("Read");
+ authDecBean.setActions(Collections.singletonList(actionBean));
+ callback.setAuthDecisionStatementData(Collections.singletonList(authDecBean));
+
+ AuthenticationStatementBean authBean = new AuthenticationStatementBean();
+ authBean.setSubject(subjectBean);
+ authBean.setAuthenticationInstant(new DateTime());
+ authBean.setSessionIndex("123456");
+ authBean.setSubject(subjectBean);
+
+ // AuthnContextClassRef is not set
+ authBean.setAuthenticationMethod(
+ "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");
+ callback.setAuthenticationStatementData(
+ Collections.singletonList(authBean));
+
+ AttributeStatementBean attrBean = new AttributeStatementBean();
+ attrBean.setSubject(subjectBean);
+
+ List<String> roles = m != null
+ ? CastUtils.<String>cast((List<?>)m.getContextualProperty("saml.roles")) : null;
+ if (roles == null) {
+ roles = Collections.singletonList("user");
+ }
+ List<AttributeBean> claims = new ArrayList<AttributeBean>();
+ AttributeBean roleClaim = new AttributeBean();
+ roleClaim.setSimpleName("subject-role");
+ roleClaim.setQualifiedName(SAMLClaim.SAML_ROLE_ATTRIBUTENAME_DEFAULT);
+ roleClaim.setNameFormat(SAML2Constants.ATTRNAME_FORMAT_UNSPECIFIED);
+ roleClaim.setAttributeValues(new ArrayList<Object>(roles));
+ claims.add(roleClaim);
+
+ List<String> authMethods =
+ m != null ? CastUtils.<String>cast((List<?>)m.getContextualProperty("saml.auth")) : null;
+ if (authMethods == null) {
+ authMethods = Collections.singletonList("password");
+ }
+
+ AttributeBean authClaim = new AttributeBean();
+ authClaim.setSimpleName("http://claims/authentication");
+ authClaim.setQualifiedName("http://claims/authentication");
+ authClaim.setNameFormat("http://claims/authentication-format");
+ authClaim.setAttributeValues(new ArrayList<Object>(authMethods));
+ claims.add(authClaim);
+
+ attrBean.setSamlAttributes(claims);
+ callback.setAttributeStatementData(Collections.singletonList(attrBean));
+
+ if (signAssertion) {
+ try {
+ Crypto crypto = CryptoFactory.getInstance(cryptoPropertiesFile);
+ callback.setIssuerCrypto(crypto);
+ callback.setIssuerKeyName(issuerKeyName);
+ callback.setIssuerKeyPassword(issuerKeyPassword);
+ callback.setSignAssertion(true);
+ } catch (WSSecurityException e) {
+ throw new IOException(e);
+ }
+ }
+ }
+ }
+ }
+
+ public String getCryptoPropertiesFile() {
+ return cryptoPropertiesFile;
+ }
+
+ public void setCryptoPropertiesFile(String cryptoPropertiesFile) {
+ this.cryptoPropertiesFile = cryptoPropertiesFile;
+ }
+
+ public String getIssuerKeyName() {
+ return issuerKeyName;
+ }
+
+ public void setIssuerKeyName(String issuerKeyName) {
+ this.issuerKeyName = issuerKeyName;
+ }
+
+ public String getIssuerKeyPassword() {
+ return issuerKeyPassword;
+ }
+
+ public void setIssuerKeyPassword(String issuerKeyPassword) {
+ this.issuerKeyPassword = issuerKeyPassword;
+ }
+
+ public String getIssuer() {
+ return issuer;
+ }
+
+ public void setIssuer(String issuer) {
+ this.issuer = issuer;
+ }
+
+ public String getAudience() {
+ return audience;
+ }
+
+ public void setAudience(String audience) {
+ this.audience = audience;
+ }
+
+ public void setConfirmationMethod(String confMethod) {
+ this.confirmationMethod = confMethod;
+ }
+
+ public boolean isSaml2() {
+ return saml2;
+ }
+
+ public void setSaml2(boolean saml2) {
+ this.saml2 = saml2;
+ }
+
+ public String getSubjectName() {
+ return subjectName;
+ }
+
+ public void setSubjectName(String subjectName) {
+ this.subjectName = subjectName;
+ }
+
+}
[5/5] cxf git commit: Prevent an ArrayIndexOutOfBoundsException on an
empty token
Posted by co...@apache.org.
Prevent an ArrayIndexOutOfBoundsException on an empty token
Project: http://git-wip-us.apache.org/repos/asf/cxf/repo
Commit: http://git-wip-us.apache.org/repos/asf/cxf/commit/59169979
Tree: http://git-wip-us.apache.org/repos/asf/cxf/tree/59169979
Diff: http://git-wip-us.apache.org/repos/asf/cxf/diff/59169979
Branch: refs/heads/master
Commit: 591699793f0a995046da04757f7c498b044a7e57
Parents: 343d06d
Author: Colm O hEigeartaigh <co...@apache.org>
Authored: Wed Jan 20 11:58:10 2016 +0000
Committer: Colm O hEigeartaigh <co...@apache.org>
Committed: Wed Jan 20 15:00:59 2016 +0000
----------------------------------------------------------------------
.../apache/cxf/rs/security/oauth2/filters/OAuthRequestFilter.java | 3 +++
1 file changed, 3 insertions(+)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cxf/blob/59169979/rt/rs/security/oauth-parent/oauth2/src/main/java/org/apache/cxf/rs/security/oauth2/filters/OAuthRequestFilter.java
----------------------------------------------------------------------
diff --git a/rt/rs/security/oauth-parent/oauth2/src/main/java/org/apache/cxf/rs/security/oauth2/filters/OAuthRequestFilter.java b/rt/rs/security/oauth-parent/oauth2/src/main/java/org/apache/cxf/rs/security/oauth2/filters/OAuthRequestFilter.java
index ae34c58..3963a1f 100644
--- a/rt/rs/security/oauth-parent/oauth2/src/main/java/org/apache/cxf/rs/security/oauth2/filters/OAuthRequestFilter.java
+++ b/rt/rs/security/oauth-parent/oauth2/src/main/java/org/apache/cxf/rs/security/oauth2/filters/OAuthRequestFilter.java
@@ -87,6 +87,9 @@ public class OAuthRequestFilter extends AbstractAccessTokenValidator
// WWW-Authenticate with the list of supported schemes will be sent back
// if the scheme is not accepted
String[] authParts = getAuthorizationParts(m);
+ if (authParts.length < 2) {
+ throw ExceptionUtils.toForbiddenException(null, null);
+ }
String authScheme = authParts[0];
String authSchemeData = authParts[1];