You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tomee.apache.org by ra...@apache.org on 2019/01/09 17:25:48 UTC

[tomee] branch master updated (340c637 -> 38ebd25)

This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git.


    from 340c637  Merge pull request #323 from otaviojava/optmizes_try_catch
     new 6e37459  TOMEE-2365 - Added project for EE Security JSR-375 implementation.
     new f5f202b  TOMEE-2365 - Added initial test to setup module.
     new 7dad419  TOMEE-2365 - Replaced ApplicationComposer with TomEE Embedded.
     new a3e8dce  TOMEE-2365 - Initial implementation classes with ServerAuthModule to support Security spec Authentication Mechanisms.
     new dc81bb9  TOMEE-2365 - Initial API code.
     new 7aa11b3  TOMEE-2365 - Added IdentityStore API.
     new c33ad08  TOMEE-2365 - Implemented default IdentifyStoreHandler.
     new cdd673a  TOMEE-2365 - Added credentials API for Basic Auth.
     new e753603  TOMEE-2365 - Added HttpMessageContext wrapper API.
     new 5df4e8f  TOMEE-2365 - CDI Extension to register AuthenticationMechanism if definitions are found.
     new 36543b8  TOMEE-2365 - Only register JASPIC provider if AuthenticationMechanism exist in the CDI context.
     new f1315f6  TOMEE-2365 - Added default IdentityStore.
     new a6b99d9  TOMEE-2365 - Basic Auth test.
     new 839c85e  TOMEE-2365 - Fixed Authorization header read.
     new c57e6dd  TOMEE-2365 - Additional bean to map Servlets to their Authentication Mechanisms.
     new 8f15bd3  TOMEE-2365 - Fixed Basic header parsing.
     new 369fc95  TOMEE-2365 - Test to load users to in-memory database.
     new 627224f  TOMEE-2365 - Properly override validate method on default Identity Store.
     new 7366bbd  TOMEE-2365 - Initial implementation of HttpMessageContext. Not complete yet, just basic stuff.
     new 868ea32  TOMEE-2365 - Implementation of validateRequest delegating to the proper CDI bean.
     new a88d557  TOMEE-2365 - Propagate CallbackHandler to perform authentication.
     new 8fa7252  TOMEE-2365 - Fixed NPE on empty Authorization header.
     new e83f7ff  TOMEE-2365 - Added a Default Authentication Mechanism to passthrough request to Servlet that don't require authentication.
     new a465769  TOMEE-2365 - Test servlet without authentication.
     new b485d4b  TOMEE-2365 - Refactored tests to be more scalable.
     new 0c8ec2b  TOMEE-2365 - Additional tests to Basic Authentication.
     new 200a84e  TOMEE-2365 - Initial implementation and wiring of FormAuthenticationMechanism.
     new 6f8a939  TOMEE-2365 - Allow a generic authentication mechanism for the entire app or specific ones per servlet.
     new fe9fab6  TOMEE-2365 - Skeleton implementation for the LoginToContinueInterceptor.
     new f4b8c03  TOMEE-2365 - Added way to inject LoginToContinue when required by the specific AuthenticationMechanism.
     new 73f975b  TOMEE-2365 - First step of FormAuthentication. Forward to login page.
     new f0c4fa7  TOMEE-2365 - Added HtmlUnit to test authentication form.
     new 199b352  TOMEE-2365 - Save original request on first form login step.
     new c5c8a3e  TOMEE-2365 - Perform authentication on the second step of the form.
     new 6121de4  TOMEE-2365 - Actual implementation of the form authentication validation.
     new e635b26  TOMEE-2365 - Final step of form authentication. Retrieve original request and authentication data and pass it to the original requested resource.
     new 0f046f5  TOMEE-2365 - Simplified test.
     new ab0eb4c  TOMEE-2365 - Removed unneeded methods.
     new b4c85be  TOMEE-2365 - Added AutoApplySession annotation to the API.
     new 4294930  TOMEE-2365 - Implemented AutoApplySessionInterceptor.
     new 99318c8  TOMEE-2365 - AutoApplySession to FormAuthentication to keep session.
     new 99d6f10  TOMEE-2365 - Values for layer and appContext.
     new cbc6f42  TOMEE-2365 - Moved AbstractTomEESecurityTest to the base package.
     new 3281fa4  TOMEE-2365 - MessageInfo to pass AuthenticationParameters for SecurityContext.
     new e0eea23  TOMEE-2365 - Improved exception message on multiple HttpAuthenticationMechanism.
     new 8242f23  TOMEE-2365 - Default appContext to root when context path is empty.
     new 62431cf  TOMEE-2365 - Fixed layer and appContextId with values used by Tomcat.
     new 38ebd25  TOMEE-2365 - Fixed tests.

The 48 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 tomee/pom.xml                                      |   1 +
 tomee/tomee-security/pom.xml                       |  74 +++++++
 .../enterprise/AuthenticationException.java        |  39 ++++
 .../security/enterprise/AuthenticationStatus.java  |  24 +++
 .../javax/security/enterprise/CallerPrincipal.java |  35 ++++
 .../mechanism/http/AuthenticationParameters.java   |  68 ++++++
 .../mechanism/http/AutoApplySession.java           |  32 +++
 .../BasicAuthenticationMechanismDefinition.java    |  29 +++
 ...ustomFormAuthenticationMechanismDefinition.java |  31 +++
 .../FormAuthenticationMechanismDefinition.java     |  31 +++
 .../http/HttpAuthenticationMechanism.java          |  42 ++++
 .../mechanism/http/HttpMessageContext.java         |  77 +++++++
 .../mechanism/http/HttpMessageContextWrapper.java  | 159 ++++++++++++++
 .../mechanism/http/LoginToContinue.java            |  44 ++++
 .../credential/AbstractClearableCredential.java    |  39 ++++
 .../credential/BasicAuthenticationCredential.java  |  67 ++++++
 .../security/enterprise/credential/Credential.java |  29 +++
 .../security/enterprise/credential/Password.java   |  56 +++++
 .../credential/UsernamePasswordCredential.java     |  54 +++++
 .../identitystore/CredentialValidationResult.java  | 119 +++++++++++
 .../enterprise/identitystore/IdentityStore.java    |  61 ++++++
 .../identitystore/IdentityStoreHandler.java        |  23 ++
 .../security/cdi/AutoApplySessionInterceptor.java  |  76 +++++++
 .../security/cdi/BasicAuthenticationMechanism.java |  74 +++++++
 .../cdi/DefaultAuthenticationMechanism.java        |  68 ++++++
 .../security/cdi/FormAuthenticationMechanism.java  |  70 +++++++
 .../security/cdi/LoginToContinueInterceptor.java   | 169 +++++++++++++++
 .../tomee/security/cdi/TomEESecurityExtension.java | 139 ++++++++++++
 ...curityServletAuthenticationMechanismMapper.java |  88 ++++++++
 .../security/http/LoginToContinueMechanism.java    | 144 +++++++++++++
 .../tomee/security/http/SavedAuthentication.java   |  41 ++++
 .../security/http/SavedHttpServletRequest.java     |  34 +++
 .../apache/tomee/security/http/SavedRequest.java   | 178 ++++++++++++++++
 .../security/http/TomEEHttpMessageContext.java     | 232 +++++++++++++++++++++
 .../identitystore/TomEEDefaultIdentityStore.java   |  71 +++++++
 .../identitystore/TomEEIdentityStoreHandler.java   | 103 +++++++++
 .../tomee/security/message/TomEEMessageInfo.java   |  41 ++++
 .../provider/TomEESecurityAuthConfigProvider.java  |  44 ++++
 .../provider/TomEESecurityServerAuthConfig.java    |  69 ++++++
 .../provider/TomEESecurityServerAuthContext.java   |  52 +++++
 .../provider/TomEESecurityServerAuthModule.java    | 109 ++++++++++
 .../TomEESecurityServletContainerInitializer.java  |  43 ++++
 .../services/javax.enterprise.inject.spi.Extension |  33 +++
 .../javax.servlet.ServletContainerInitializer      |  17 ++
 .../tomee/security/AbstractTomEESecurityTest.java  |  48 +++++
 .../tomee/security/client/BasicAuthFilter.java     |  41 ++++
 .../security/servlet/BasicAuthServletTest.java     |  92 ++++++++
 .../security/servlet/FormAuthServletTest.java      | 107 ++++++++++
 .../tomee/security/servlet/SimpleServletTest.java  |  53 +++++
 .../src/test}/resources/META-INF/beans.xml         |   0
 .../src/test/resources/conf/server.xml             | 166 +++++++++++++++
 .../src/test/resources/conf/tomcat-users.xml       |  20 ++
 52 files changed, 3556 insertions(+)
 create mode 100644 tomee/tomee-security/pom.xml
 create mode 100644 tomee/tomee-security/src/main/java/javax/security/enterprise/AuthenticationException.java
 create mode 100644 tomee/tomee-security/src/main/java/javax/security/enterprise/AuthenticationStatus.java
 create mode 100644 tomee/tomee-security/src/main/java/javax/security/enterprise/CallerPrincipal.java
 create mode 100644 tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/AuthenticationParameters.java
 create mode 100644 tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/AutoApplySession.java
 create mode 100644 tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/BasicAuthenticationMechanismDefinition.java
 create mode 100644 tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/CustomFormAuthenticationMechanismDefinition.java
 create mode 100644 tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/FormAuthenticationMechanismDefinition.java
 create mode 100644 tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/HttpAuthenticationMechanism.java
 create mode 100644 tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/HttpMessageContext.java
 create mode 100644 tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/HttpMessageContextWrapper.java
 create mode 100644 tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/LoginToContinue.java
 create mode 100644 tomee/tomee-security/src/main/java/javax/security/enterprise/credential/AbstractClearableCredential.java
 create mode 100644 tomee/tomee-security/src/main/java/javax/security/enterprise/credential/BasicAuthenticationCredential.java
 create mode 100644 tomee/tomee-security/src/main/java/javax/security/enterprise/credential/Credential.java
 create mode 100644 tomee/tomee-security/src/main/java/javax/security/enterprise/credential/Password.java
 create mode 100644 tomee/tomee-security/src/main/java/javax/security/enterprise/credential/UsernamePasswordCredential.java
 create mode 100644 tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/CredentialValidationResult.java
 create mode 100644 tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/IdentityStore.java
 create mode 100644 tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/IdentityStoreHandler.java
 create mode 100644 tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/AutoApplySessionInterceptor.java
 create mode 100644 tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/BasicAuthenticationMechanism.java
 create mode 100644 tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/DefaultAuthenticationMechanism.java
 create mode 100644 tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/FormAuthenticationMechanism.java
 create mode 100644 tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/LoginToContinueInterceptor.java
 create mode 100644 tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityExtension.java
 create mode 100644 tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityServletAuthenticationMechanismMapper.java
 create mode 100644 tomee/tomee-security/src/main/java/org/apache/tomee/security/http/LoginToContinueMechanism.java
 create mode 100644 tomee/tomee-security/src/main/java/org/apache/tomee/security/http/SavedAuthentication.java
 create mode 100644 tomee/tomee-security/src/main/java/org/apache/tomee/security/http/SavedHttpServletRequest.java
 create mode 100644 tomee/tomee-security/src/main/java/org/apache/tomee/security/http/SavedRequest.java
 create mode 100644 tomee/tomee-security/src/main/java/org/apache/tomee/security/http/TomEEHttpMessageContext.java
 create mode 100644 tomee/tomee-security/src/main/java/org/apache/tomee/security/identitystore/TomEEDefaultIdentityStore.java
 create mode 100644 tomee/tomee-security/src/main/java/org/apache/tomee/security/identitystore/TomEEIdentityStoreHandler.java
 create mode 100644 tomee/tomee-security/src/main/java/org/apache/tomee/security/message/TomEEMessageInfo.java
 create mode 100644 tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityAuthConfigProvider.java
 create mode 100644 tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityServerAuthConfig.java
 create mode 100644 tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityServerAuthContext.java
 create mode 100644 tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityServerAuthModule.java
 create mode 100644 tomee/tomee-security/src/main/java/org/apache/tomee/security/servlet/TomEESecurityServletContainerInitializer.java
 create mode 100644 tomee/tomee-security/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension
 create mode 100644 tomee/tomee-security/src/main/resources/META-INF/services/javax.servlet.ServletContainerInitializer
 create mode 100644 tomee/tomee-security/src/test/java/org/apache/tomee/security/AbstractTomEESecurityTest.java
 create mode 100644 tomee/tomee-security/src/test/java/org/apache/tomee/security/client/BasicAuthFilter.java
 create mode 100644 tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/BasicAuthServletTest.java
 create mode 100644 tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/FormAuthServletTest.java
 create mode 100644 tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java
 copy {examples/mp-config-example/src/main => tomee/tomee-security/src/test}/resources/META-INF/beans.xml (100%)
 create mode 100644 tomee/tomee-security/src/test/resources/conf/server.xml
 create mode 100644 tomee/tomee-security/src/test/resources/conf/tomcat-users.xml


[tomee] 41/48: TOMEE-2365 - AutoApplySession to FormAuthentication to keep session.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit 99318c82e346f4cbc4c8467f7fd140dfaf88c5c5
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Mon Jan 7 17:05:26 2019 +0000

    TOMEE-2365 - AutoApplySession to FormAuthentication to keep session.
---
 .../java/org/apache/tomee/security/cdi/FormAuthenticationMechanism.java | 2 ++
 .../java/org/apache/tomee/security/servlet/FormAuthServletTest.java     | 2 ++
 2 files changed, 4 insertions(+)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/FormAuthenticationMechanism.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/FormAuthenticationMechanism.java
index 08f482b..1bdd60f 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/FormAuthenticationMechanism.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/FormAuthenticationMechanism.java
@@ -22,6 +22,7 @@ import javax.enterprise.context.ApplicationScoped;
 import javax.inject.Inject;
 import javax.security.enterprise.AuthenticationException;
 import javax.security.enterprise.AuthenticationStatus;
+import javax.security.enterprise.authentication.mechanism.http.AutoApplySession;
 import javax.security.enterprise.authentication.mechanism.http.HttpAuthenticationMechanism;
 import javax.security.enterprise.authentication.mechanism.http.HttpMessageContext;
 import javax.security.enterprise.authentication.mechanism.http.LoginToContinue;
@@ -33,6 +34,7 @@ import javax.ws.rs.HttpMethod;
 import java.util.function.Supplier;
 
 @ApplicationScoped
+@AutoApplySession
 @LoginToContinue
 public class FormAuthenticationMechanism implements HttpAuthenticationMechanism, LoginToContinueMechanism {
     @Inject
diff --git a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/FormAuthServletTest.java b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/FormAuthServletTest.java
index 4a8ccf7..1fd6f7e 100644
--- a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/FormAuthServletTest.java
+++ b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/FormAuthServletTest.java
@@ -50,6 +50,8 @@ public class FormAuthServletTest extends AbstractTomEESecurityTest {
         final Page result = login.getInputByName("submit").click();
         assertEquals(200, result.getWebResponse().getStatusCode());
         assertEquals("ok!", result.getWebResponse().getContentAsString());
+
+        assertEquals("ok!", webClient.getPage(getAppUrl() + "/form").getWebResponse().getContentAsString());
     }
 
     @ApplicationScoped


[tomee] 44/48: TOMEE-2365 - MessageInfo to pass AuthenticationParameters for SecurityContext.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit 3281fa45dee7bc80fe4d59e646b6569df4114cbb
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Tue Jan 8 18:53:40 2019 +0000

    TOMEE-2365 - MessageInfo to pass AuthenticationParameters for SecurityContext.
---
 .../security/http/TomEEHttpMessageContext.java     |  5 ++-
 .../tomee/security/message/TomEEMessageInfo.java   | 41 ++++++++++++++++++++++
 2 files changed, 45 insertions(+), 1 deletion(-)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/TomEEHttpMessageContext.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/TomEEHttpMessageContext.java
index d67d74d..f6c25d4 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/TomEEHttpMessageContext.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/TomEEHttpMessageContext.java
@@ -17,6 +17,7 @@
 package org.apache.tomee.security.http;
 
 import org.apache.catalina.authenticator.jaspic.MessageInfoImpl;
+import org.apache.tomee.security.message.TomEEMessageInfo;
 
 import javax.security.auth.Subject;
 import javax.security.auth.callback.Callback;
@@ -99,7 +100,9 @@ public class TomEEHttpMessageContext implements HttpMessageContext {
 
     @Override
     public AuthenticationParameters getAuthParameters() {
-        return new AuthenticationParameters();
+        return (AuthenticationParameters) messageInfo.getMap()
+                                                     .getOrDefault(TomEEMessageInfo.AUTH_PARAMS,
+                                                                   new AuthenticationParameters());
     }
 
     @Override
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/message/TomEEMessageInfo.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/message/TomEEMessageInfo.java
new file mode 100644
index 0000000..1c4c989
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/message/TomEEMessageInfo.java
@@ -0,0 +1,41 @@
+/*
+ * 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.tomee.security.message;
+
+import org.apache.catalina.authenticator.jaspic.MessageInfoImpl;
+
+import javax.security.enterprise.authentication.mechanism.http.AuthenticationParameters;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+public class TomEEMessageInfo extends MessageInfoImpl {
+    public static final String AUTH_PARAMS = "org.apache.tomee.security.context.authParams";
+
+    public TomEEMessageInfo(final HttpServletRequest request,
+                            final HttpServletResponse response,
+                            final boolean authMandatory) {
+        super(request, response, authMandatory);
+    }
+
+    public TomEEMessageInfo(final HttpServletRequest request,
+                            final HttpServletResponse response,
+                            final boolean authMandatory,
+                            final AuthenticationParameters authParameters) {
+        super(request, response, authMandatory);
+        getMap().put(AUTH_PARAMS, authParameters);
+    }
+}


[tomee] 28/48: TOMEE-2365 - Allow a generic authentication mechanism for the entire app or specific ones per servlet.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit 6f8a939a7428f1c8164b26cadf469411148f14ac
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Thu Dec 27 12:32:49 2018 +0000

    TOMEE-2365 - Allow a generic authentication mechanism for the entire app or specific ones per servlet.
---
 .../cdi/DefaultAuthenticationMechanism.java        | 37 ++++++++++++++++++++--
 ...curityServletAuthenticationMechanismMapper.java | 16 ++++++++++
 2 files changed, 51 insertions(+), 2 deletions(-)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/DefaultAuthenticationMechanism.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/DefaultAuthenticationMechanism.java
index f7da0a6..54bb000 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/DefaultAuthenticationMechanism.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/DefaultAuthenticationMechanism.java
@@ -26,23 +26,56 @@ import javax.servlet.http.HttpServletResponse;
 
 @ApplicationScoped
 public class DefaultAuthenticationMechanism implements HttpAuthenticationMechanism {
+    private HttpAuthenticationMechanism delegate;
+
+    public DefaultAuthenticationMechanism() {
+        this.delegate = new EmptyAuthenticationMechanism();
+    }
+
     @Override
     public AuthenticationStatus validateRequest(final HttpServletRequest request, final HttpServletResponse response,
                                                 final HttpMessageContext httpMessageContext)
             throws AuthenticationException {
-        return httpMessageContext.doNothing();
+        return delegate.validateRequest(request, response, httpMessageContext);
     }
 
     @Override
     public AuthenticationStatus secureResponse(final HttpServletRequest request, final HttpServletResponse response,
                                                final HttpMessageContext httpMessageContext)
             throws AuthenticationException {
-        return null;
+        return delegate.secureResponse(request, response, httpMessageContext);
     }
 
     @Override
     public void cleanSubject(final HttpServletRequest request, final HttpServletResponse response,
                              final HttpMessageContext httpMessageContext) {
+        delegate.cleanSubject(request, response, httpMessageContext);
+    }
+
+    public void setDelegate(final HttpAuthenticationMechanism delegate) {
+        this.delegate = delegate;
+    }
+
+    private static class EmptyAuthenticationMechanism implements HttpAuthenticationMechanism {
+        @Override
+        public AuthenticationStatus validateRequest(final HttpServletRequest request,
+                                                    final HttpServletResponse response,
+                                                    final HttpMessageContext httpMessageContext)
+                throws AuthenticationException {
+            return httpMessageContext.doNothing();
+        }
+
+        @Override
+        public AuthenticationStatus secureResponse(final HttpServletRequest request, final HttpServletResponse response,
+                                                   final HttpMessageContext httpMessageContext)
+                throws AuthenticationException {
+            return httpMessageContext.doNothing();
+        }
+
+        @Override
+        public void cleanSubject(final HttpServletRequest request, final HttpServletResponse response,
+                                 final HttpMessageContext httpMessageContext) {
 
+        }
     }
 }
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityServletAuthenticationMechanismMapper.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityServletAuthenticationMechanismMapper.java
index fff782e..d054783 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityServletAuthenticationMechanismMapper.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityServletAuthenticationMechanismMapper.java
@@ -19,6 +19,7 @@ package org.apache.tomee.security.cdi;
 import javax.enterprise.context.ApplicationScoped;
 import javax.enterprise.context.Initialized;
 import javax.enterprise.event.Observes;
+import javax.enterprise.inject.Instance;
 import javax.enterprise.inject.spi.CDI;
 import javax.inject.Inject;
 import javax.security.enterprise.authentication.mechanism.http.BasicAuthenticationMechanismDefinition;
@@ -27,13 +28,17 @@ import javax.security.enterprise.authentication.mechanism.http.HttpAuthenticatio
 import javax.servlet.ServletContext;
 import javax.servlet.ServletRegistration;
 import java.util.Map;
+import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
+import java.util.stream.Collectors;
 
 @ApplicationScoped
 public class TomEESecurityServletAuthenticationMechanismMapper {
     private final Map<String, HttpAuthenticationMechanism> servletAuthenticationMapper = new ConcurrentHashMap<>();
 
     @Inject
+    private Instance<HttpAuthenticationMechanism> authenticationMechanisms;
+    @Inject
     private DefaultAuthenticationMechanism defaultAuthenticationMechanism;
 
     public void init(@Observes @Initialized(ApplicationScoped.class) final ServletContext context) {
@@ -55,6 +60,17 @@ public class TomEESecurityServletAuthenticationMechanismMapper {
                 // Ignore
             }
         });
+
+        final Set<HttpAuthenticationMechanism> availableBeans =
+                authenticationMechanisms.stream().collect(Collectors.toSet());
+        availableBeans.removeAll(servletAuthenticationMapper.values());
+        availableBeans.remove(defaultAuthenticationMechanism);
+
+        if (availableBeans.size() == 1) {
+            defaultAuthenticationMechanism.setDelegate(availableBeans.iterator().next());
+        } else if (availableBeans.size() > 1) {
+            throw new IllegalStateException();
+        }
     }
 
     public HttpAuthenticationMechanism getCurrentAuthenticationMechanism(final String servletName) {


[tomee] 23/48: TOMEE-2365 - Added a Default Authentication Mechanism to passthrough request to Servlet that don't require authentication.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit e83f7ff99f18f16cceb6fb01deb12d5af27248de
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Wed Dec 26 18:59:11 2018 +0000

    TOMEE-2365 - Added a Default Authentication Mechanism to passthrough request to Servlet that don't require authentication.
---
 .../cdi/DefaultAuthenticationMechanism.java        | 48 ++++++++++++++++++++++
 .../tomee/security/cdi/TomEESecurityExtension.java |  5 +++
 ...curityServletAuthenticationMechanismMapper.java |  6 ++-
 .../TomEESecurityServletContainerInitializer.java  | 16 +++++---
 4 files changed, 68 insertions(+), 7 deletions(-)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/DefaultAuthenticationMechanism.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/DefaultAuthenticationMechanism.java
new file mode 100644
index 0000000..f7da0a6
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/DefaultAuthenticationMechanism.java
@@ -0,0 +1,48 @@
+/*
+ * 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.tomee.security.cdi;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.security.enterprise.AuthenticationException;
+import javax.security.enterprise.AuthenticationStatus;
+import javax.security.enterprise.authentication.mechanism.http.HttpAuthenticationMechanism;
+import javax.security.enterprise.authentication.mechanism.http.HttpMessageContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+@ApplicationScoped
+public class DefaultAuthenticationMechanism implements HttpAuthenticationMechanism {
+    @Override
+    public AuthenticationStatus validateRequest(final HttpServletRequest request, final HttpServletResponse response,
+                                                final HttpMessageContext httpMessageContext)
+            throws AuthenticationException {
+        return httpMessageContext.doNothing();
+    }
+
+    @Override
+    public AuthenticationStatus secureResponse(final HttpServletRequest request, final HttpServletResponse response,
+                                               final HttpMessageContext httpMessageContext)
+            throws AuthenticationException {
+        return null;
+    }
+
+    @Override
+    public void cleanSubject(final HttpServletRequest request, final HttpServletResponse response,
+                             final HttpMessageContext httpMessageContext) {
+
+    }
+}
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityExtension.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityExtension.java
index 3470bd2..712587e 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityExtension.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityExtension.java
@@ -49,6 +49,7 @@ public class TomEESecurityExtension implements Extension {
     void observeBeforeBeanDiscovery(@Observes final BeforeBeanDiscovery beforeBeanDiscovery,
                                     final BeanManager beanManager) {
         if (basicAuthentication.isEmpty()) {
+            beforeBeanDiscovery.addAnnotatedType(beanManager.createAnnotatedType(DefaultAuthenticationMechanism.class));
             beforeBeanDiscovery.addAnnotatedType(
                     beanManager.createAnnotatedType(TomEESecurityServletAuthenticationMechanismMapper.class));
             beforeBeanDiscovery.addAnnotatedType(beanManager.createAnnotatedType(TomEEDefaultIdentityStore.class));
@@ -76,4 +77,8 @@ public class TomEESecurityExtension implements Extension {
                });
         }
     }
+
+    public boolean hasAuthenticationMechanisms() {
+        return !basicAuthentication.isEmpty();
+    }
 }
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityServletAuthenticationMechanismMapper.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityServletAuthenticationMechanismMapper.java
index bbad8ef..836fff4 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityServletAuthenticationMechanismMapper.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityServletAuthenticationMechanismMapper.java
@@ -20,6 +20,7 @@ import javax.enterprise.context.ApplicationScoped;
 import javax.enterprise.context.Initialized;
 import javax.enterprise.event.Observes;
 import javax.enterprise.inject.spi.CDI;
+import javax.inject.Inject;
 import javax.security.enterprise.authentication.mechanism.http.BasicAuthenticationMechanismDefinition;
 import javax.security.enterprise.authentication.mechanism.http.HttpAuthenticationMechanism;
 import javax.servlet.ServletContext;
@@ -31,6 +32,9 @@ import java.util.concurrent.ConcurrentHashMap;
 public class TomEESecurityServletAuthenticationMechanismMapper {
     private final Map<String, HttpAuthenticationMechanism> servletAuthenticationMapper = new ConcurrentHashMap<>();
 
+    @Inject
+    private DefaultAuthenticationMechanism defaultAuthenticationMechanism;
+
     public void init(@Observes @Initialized(ApplicationScoped.class) final ServletContext context) {
         final Map<String, ? extends ServletRegistration> servletRegistrations = context.getServletRegistrations();
         servletRegistrations.forEach((servletName, servletRegistration) -> {
@@ -47,6 +51,6 @@ public class TomEESecurityServletAuthenticationMechanismMapper {
     }
 
     public HttpAuthenticationMechanism getCurrentAuthenticationMechanism(final String servletName) {
-        return servletAuthenticationMapper.get(servletName);
+        return servletAuthenticationMapper.getOrDefault(servletName, defaultAuthenticationMechanism);
     }
 }
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/servlet/TomEESecurityServletContainerInitializer.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/servlet/TomEESecurityServletContainerInitializer.java
index 7eba191..6dc9b25 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/servlet/TomEESecurityServletContainerInitializer.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/servlet/TomEESecurityServletContainerInitializer.java
@@ -16,23 +16,27 @@
  */
 package org.apache.tomee.security.servlet;
 
+import org.apache.tomee.security.cdi.TomEESecurityExtension;
 import org.apache.tomee.security.provider.TomEESecurityAuthConfigProvider;
 
 import javax.enterprise.inject.spi.CDI;
+import javax.inject.Inject;
 import javax.security.auth.message.config.AuthConfigFactory;
-import javax.security.enterprise.authentication.mechanism.http.HttpAuthenticationMechanism;
 import javax.servlet.ServletContainerInitializer;
 import javax.servlet.ServletContext;
 import javax.servlet.ServletException;
+import java.util.Optional;
 import java.util.Set;
 
 public class TomEESecurityServletContainerInitializer implements ServletContainerInitializer {
     @Override
     public void onStartup(final Set<Class<?>> c, final ServletContext ctx) throws ServletException {
-        if (CDI.current().select(HttpAuthenticationMechanism.class).isResolvable()) {
-            AuthConfigFactory.getFactory()
-                             .registerConfigProvider(new TomEESecurityAuthConfigProvider(), null, null,
-                                                     "TomEE Security JSR-375");
-        }
+        Optional.ofNullable(CDI.current().getBeanManager().getExtension(TomEESecurityExtension.class))
+                .map(TomEESecurityExtension::hasAuthenticationMechanisms)
+                .filter(has -> has.equals(true))
+                .ifPresent(has -> AuthConfigFactory.getFactory()
+                                                   .registerConfigProvider(new TomEESecurityAuthConfigProvider(),
+                                                                           null, null,
+                                                                           "TomEE Security JSR-375"));
     }
 }


[tomee] 02/48: TOMEE-2365 - Added initial test to setup module.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit f5f202b027a4dc58e4e37a9a503c531df209a9c9
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Fri Dec 14 15:16:14 2018 +0000

    TOMEE-2365 - Added initial test to setup module.
---
 tomee/tomee-security/pom.xml                       |  9 ++-
 .../tomee/security/servlet/SimpleServletTest.java  | 78 ++++++++++++++++++++++
 2 files changed, 86 insertions(+), 1 deletion(-)

diff --git a/tomee/tomee-security/pom.xml b/tomee/tomee-security/pom.xml
index 064e5bb..d7943de 100644
--- a/tomee/tomee-security/pom.xml
+++ b/tomee/tomee-security/pom.xml
@@ -37,7 +37,14 @@
     <dependency>
       <groupId>${project.groupId}</groupId>
       <artifactId>javaee-api</artifactId>
-      <classifier>tomcat</classifier>
+    </dependency>
+    <dependency>
+      <groupId>${project.groupId}</groupId>
+      <artifactId>openejb-server</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>${project.groupId}</groupId>
+      <artifactId>openejb-http</artifactId>
     </dependency>
   </dependencies>
 </project>
diff --git a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java
new file mode 100644
index 0000000..08e3c6d
--- /dev/null
+++ b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java
@@ -0,0 +1,78 @@
+/*
+ * 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.tomee.security.servlet;
+
+import org.apache.openejb.jee.WebApp;
+import org.apache.openejb.junit.ApplicationComposer;
+import org.apache.openejb.loader.IO;
+import org.apache.openejb.testing.Classes;
+import org.apache.openejb.testing.Configuration;
+import org.apache.openejb.testing.EnableServices;
+import org.apache.openejb.testing.Module;
+import org.apache.openejb.testng.PropertiesBuilder;
+import org.apache.openejb.util.NetworkUtil;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import javax.servlet.ServletException;
+import javax.servlet.annotation.WebServlet;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.net.URL;
+import java.util.Properties;
+
+import static org.junit.Assert.assertEquals;
+
+@RunWith(ApplicationComposer.class)
+@EnableServices("http")
+public class SimpleServletTest {
+    private static int port = -1;
+
+    @BeforeClass
+    public static void beforeClass() {
+        port = NetworkUtil.getNextAvailablePort();
+    }
+
+    @Configuration
+    public Properties props() {
+        return new PropertiesBuilder().p("httpejbd.port", Integer.toString(port)).build();
+    }
+
+    @Module
+    @Classes(TestServlet.class)
+    public WebApp app() {
+        return new WebApp().contextRoot("/servlet");
+    }
+
+    @Test
+    public void servlet() throws Exception {
+        assertEquals("ok!", IO.slurp(new URL("http://localhost:" + port + "/servlet/test")));
+    }
+
+    @WebServlet(urlPatterns = "/test")
+    public static class TestServlet extends HttpServlet {
+        @Override
+        protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
+                throws ServletException, IOException {
+            resp.getWriter().write("ok!");
+        }
+    }
+
+}


[tomee] 37/48: TOMEE-2365 - Simplified test.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit 0f046f5354c53a9db4b68879d627794f120a299e
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Fri Dec 28 17:07:09 2018 +0000

    TOMEE-2365 - Simplified test.
---
 .../org/apache/tomee/security/servlet/AbstractTomEESecurityTest.java  | 4 ++++
 .../java/org/apache/tomee/security/servlet/FormAuthServletTest.java   | 3 +--
 2 files changed, 5 insertions(+), 2 deletions(-)

diff --git a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/AbstractTomEESecurityTest.java b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/AbstractTomEESecurityTest.java
index 7e80ce2..8999b2b 100644
--- a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/AbstractTomEESecurityTest.java
+++ b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/AbstractTomEESecurityTest.java
@@ -43,4 +43,8 @@ public abstract class AbstractTomEESecurityTest {
     public static void tearDown() throws Exception {
         container.close();
     }
+
+    protected String getAppUrl() {
+        return "http://localhost:" + container.getConfiguration().getHttpPort();
+    }
 }
diff --git a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/FormAuthServletTest.java b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/FormAuthServletTest.java
index 8a63dd6..4a8ccf7 100644
--- a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/FormAuthServletTest.java
+++ b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/FormAuthServletTest.java
@@ -40,8 +40,7 @@ public class FormAuthServletTest extends AbstractTomEESecurityTest {
     @Test
     public void authenticate() throws Exception {
         final WebClient webClient = new WebClient();
-        final HtmlPage page =
-                webClient.getPage("http://localhost:" + container.getConfiguration().getHttpPort() + "/form");
+        final HtmlPage page = webClient.getPage(getAppUrl() + "/form");
         assertEquals(200, page.getWebResponse().getStatusCode());
 
         final HtmlForm login = page.getFormByName("login");


[tomee] 26/48: TOMEE-2365 - Additional tests to Basic Authentication.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit 0c8ec2b7204f5a44edee6b3efce6b4f5f16b37ef
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Thu Dec 27 11:17:02 2018 +0000

    TOMEE-2365 - Additional tests to Basic Authentication.
---
 .../tomee/security/client/BasicAuthFilter.java     | 16 ++++++++----
 .../security/servlet/BasicAuthServletTest.java     | 30 ++++++++++++++++++++--
 .../src/test/resources/conf/tomcat-users.xml       |  1 +
 3 files changed, 40 insertions(+), 7 deletions(-)

diff --git a/tomee/tomee-security/src/test/java/org/apache/tomee/security/client/BasicAuthFilter.java b/tomee/tomee-security/src/test/java/org/apache/tomee/security/client/BasicAuthFilter.java
index 16d6322..dad3b0f 100644
--- a/tomee/tomee-security/src/test/java/org/apache/tomee/security/client/BasicAuthFilter.java
+++ b/tomee/tomee-security/src/test/java/org/apache/tomee/security/client/BasicAuthFilter.java
@@ -24,12 +24,18 @@ import java.util.Base64;
 import static javax.ws.rs.core.HttpHeaders.AUTHORIZATION;
 
 public class BasicAuthFilter implements ClientRequestFilter {
-    @Override
-    public void filter(final ClientRequestContext requestContext) throws IOException {
-        requestContext.getHeaders().add(AUTHORIZATION, basicAuth("tomcat", "tomcat"));
+    private final String username;
+    private final String password;
+
+    public BasicAuthFilter(final String username, final String password) {
+        this.username = username;
+        this.password = password;
     }
 
-    private String basicAuth(final String username, final String password) {
-        return "Basic " + new String(Base64.getEncoder().encode((username + ":" + password).getBytes()));
+    @Override
+    public void filter(final ClientRequestContext requestContext) throws IOException {
+        requestContext.getHeaders()
+                      .add(AUTHORIZATION,
+                           "Basic " + new String(Base64.getEncoder().encode((username + ":" + password).getBytes())));
     }
 }
diff --git a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/BasicAuthServletTest.java b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/BasicAuthServletTest.java
index e0fd2c6..e45e387 100644
--- a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/BasicAuthServletTest.java
+++ b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/BasicAuthServletTest.java
@@ -36,7 +36,7 @@ public class BasicAuthServletTest extends AbstractTomEESecurityTest {
     @Test
     public void authenticate() throws Exception {
         final String servlet = "http://localhost:" + container.getConfiguration().getHttpPort() + "/basic";
-        assertEquals(200, ClientBuilder.newBuilder().register(new BasicAuthFilter()).build()
+        assertEquals(200, ClientBuilder.newBuilder().register(new BasicAuthFilter("tomcat", "tomcat")).build()
                                        .target(servlet)
                                        .request()
                                        .get().getStatus());
@@ -45,13 +45,39 @@ public class BasicAuthServletTest extends AbstractTomEESecurityTest {
     @Test
     public void missingAuthorizationHeader() throws Exception {
         final String servlet = "http://localhost:" + container.getConfiguration().getHttpPort() + "/basic";
-
         assertEquals(401, ClientBuilder.newBuilder().build()
                                        .target(servlet)
                                        .request()
                                        .get().getStatus());
     }
 
+    @Test
+    public void noUser() throws Exception {
+        final String servlet = "http://localhost:" + container.getConfiguration().getHttpPort() + "/basic";
+        assertEquals(401, ClientBuilder.newBuilder().register(new BasicAuthFilter("unknown", "tomcat")).build()
+                                       .target(servlet)
+                                       .request()
+                                       .get().getStatus());
+    }
+
+    @Test
+    public void wrongPassword() throws Exception {
+        final String servlet = "http://localhost:" + container.getConfiguration().getHttpPort() + "/basic";
+        assertEquals(401, ClientBuilder.newBuilder().register(new BasicAuthFilter("tomcat", "wrong")).build()
+                                       .target(servlet)
+                                       .request()
+                                       .get().getStatus());
+    }
+
+    @Test
+    public void missingRole() throws Exception {
+        final String servlet = "http://localhost:" + container.getConfiguration().getHttpPort() + "/basic";
+        assertEquals(403, ClientBuilder.newBuilder().register(new BasicAuthFilter("user", "user")).build()
+                                       .target(servlet)
+                                       .request()
+                                       .get().getStatus());
+    }
+
     @WebServlet(urlPatterns = "/basic")
     @ServletSecurity(@HttpConstraint(rolesAllowed = "tomcat"))
     @BasicAuthenticationMechanismDefinition
diff --git a/tomee/tomee-security/src/test/resources/conf/tomcat-users.xml b/tomee/tomee-security/src/test/resources/conf/tomcat-users.xml
index f7da309..d7de203 100644
--- a/tomee/tomee-security/src/test/resources/conf/tomcat-users.xml
+++ b/tomee/tomee-security/src/test/resources/conf/tomcat-users.xml
@@ -16,4 +16,5 @@
   -->
 <tomcat-users>
   <user name="tomcat" password="tomcat" roles="tomcat"/>
+  <user name="user" password="user" roles="user"/>
 </tomcat-users>


[tomee] 17/48: TOMEE-2365 - Test to load users to in-memory database.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit 369fc953f7b4d4376c7917a4fb0b077f107984d6
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Wed Dec 26 16:14:39 2018 +0000

    TOMEE-2365 - Test to load users to in-memory database.
---
 .../tomee/security/servlet/SimpleServletTest.java  |   3 +-
 .../src/test/resources/conf/server.xml             | 166 +++++++++++++++++++++
 .../src/test/resources/conf/tomcat-users.xml       |  19 +++
 3 files changed, 187 insertions(+), 1 deletion(-)

diff --git a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java
index 2a70385..ab33b9d 100644
--- a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java
+++ b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java
@@ -43,6 +43,7 @@ public class SimpleServletTest {
     public void testWebApp() throws Exception {
         try (Container container = new Container(
                 new Configuration()
+                        .conf("conf")
                         .http(NetworkUtil.getNextAvailablePort())
                         .property("openejb.container.additional.exclude", "org.apache.tomee.security.")
                         .property("openejb.additional.include", "tomee-"))
@@ -60,7 +61,7 @@ public class SimpleServletTest {
     }
 
     @WebServlet(urlPatterns = "/servlet")
-    @ServletSecurity(@HttpConstraint(rolesAllowed = "role"))
+    @ServletSecurity(@HttpConstraint(rolesAllowed = "tomcat"))
     @BasicAuthenticationMechanismDefinition
     public static class TestServlet extends HttpServlet {
         @Override
diff --git a/tomee/tomee-security/src/test/resources/conf/server.xml b/tomee/tomee-security/src/test/resources/conf/server.xml
new file mode 100644
index 0000000..d1ac3f2
--- /dev/null
+++ b/tomee/tomee-security/src/test/resources/conf/server.xml
@@ -0,0 +1,166 @@
+<?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.
+-->
+<!-- Note:  A "Server" is not itself a "Container", so you may not
+     define subcomponents such as "Valves" at this level.
+     Documentation at /docs/config/server.html
+ -->
+<Server port="8005" shutdown="SHUTDOWN">
+  <!-- Security listener. Documentation at /docs/config/listeners.html
+  <Listener className="org.apache.catalina.security.SecurityListener" />
+  -->
+  <!--APR library loader. Documentation at /docs/apr.html -->
+  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
+  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
+  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
+  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
+  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />
+
+  <!-- Global JNDI resources
+       Documentation at /docs/jndi-resources-howto.html
+  -->
+  <GlobalNamingResources>
+    <!-- Editable user database that can also be used by
+         UserDatabaseRealm to authenticate users
+    -->
+    <Resource name="UserDatabase" auth="Container"
+              type="org.apache.catalina.UserDatabase"
+              description="User database that can be updated and saved"
+              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
+              pathname="conf/tomcat-users.xml" />
+  </GlobalNamingResources>
+
+  <!-- A "Service" is a collection of one or more "Connectors" that share
+       a single "Container" Note:  A "Service" is not itself a "Container",
+       so you may not define subcomponents such as "Valves" at this level.
+       Documentation at /docs/config/service.html
+   -->
+  <Service name="Catalina">
+
+    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
+    <!--
+    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
+        maxThreads="150" minSpareThreads="4"/>
+    -->
+
+
+    <!-- A "Connector" represents an endpoint by which requests are received
+         and responses are returned. Documentation at :
+         Java HTTP Connector: /docs/config/http.html
+         Java AJP  Connector: /docs/config/ajp.html
+         APR (HTTP/AJP) Connector: /docs/apr.html
+         Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
+    -->
+    <Connector port="8080" protocol="HTTP/1.1"
+               connectionTimeout="20000"
+               redirectPort="8443" xpoweredBy="false" server="Apache TomEE" />
+    <!-- A "Connector" using the shared thread pool-->
+    <!--
+    <Connector executor="tomcatThreadPool"
+               port="8080" protocol="HTTP/1.1"
+               connectionTimeout="20000"
+               redirectPort="8443" />
+    -->
+    <!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443
+         This connector uses the NIO implementation. The default
+         SSLImplementation will depend on the presence of the APR/native
+         library and the useOpenSSL attribute of the
+         AprLifecycleListener.
+         Either JSSE or OpenSSL style configuration may be used regardless of
+         the SSLImplementation selected. JSSE style configuration is used below.
+    -->
+    <!--
+    <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
+               maxThreads="150" SSLEnabled="true">
+        <SSLHostConfig>
+            <Certificate certificateKeystoreFile="conf/localhost-rsa.jks"
+                         type="RSA" xpoweredBy="false" server="Apache TomEE" />
+        </SSLHostConfig>
+    </Connector>
+    -->
+    <!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443 with HTTP/2
+         This connector uses the APR/native implementation which always uses
+         OpenSSL for TLS.
+         Either JSSE or OpenSSL style configuration may be used. OpenSSL style
+         configuration is used below.
+    -->
+    <!--
+    <Connector port="8443" protocol="org.apache.coyote.http11.Http11AprProtocol"
+               maxThreads="150" SSLEnabled="true" >
+        <UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" xpoweredBy="false" server="Apache TomEE" />
+        <SSLHostConfig>
+            <Certificate certificateKeyFile="conf/localhost-rsa-key.pem"
+                         certificateFile="conf/localhost-rsa-cert.pem"
+                         certificateChainFile="conf/localhost-rsa-chain.pem"
+                         type="RSA" />
+        </SSLHostConfig>
+    </Connector>
+    -->
+
+    <!-- Define an AJP 1.3 Connector on port 8009 -->
+    <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
+
+
+    <!-- An Engine represents the entry point (within Catalina) that processes
+         every request.  The Engine implementation for Tomcat stand alone
+         analyzes the HTTP headers included with the request, and passes them
+         on to the appropriate Host (virtual host).
+         Documentation at /docs/config/engine.html -->
+
+    <!-- You should set jvmRoute to support load-balancing via AJP ie :
+    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
+    -->
+    <Engine name="Catalina" defaultHost="localhost">
+
+      <!--For clustering, please take a look at documentation at:
+          /docs/cluster-howto.html  (simple how to)
+          /docs/config/cluster.html (reference documentation) -->
+      <!--
+      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
+      -->
+
+      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
+           via a brute-force attack -->
+      <Realm className="org.apache.catalina.realm.LockOutRealm">
+        <!-- This Realm uses the UserDatabase configured in the global JNDI
+             resources under the key "UserDatabase".  Any edits
+             that are performed against this UserDatabase are immediately
+             available for use by the Realm.  -->
+        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
+               resourceName="UserDatabase"/>
+      </Realm>
+
+      <Host name="localhost"  appBase="webapps"
+            unpackWARs="true" autoDeploy="true">
+
+        <!-- SingleSignOn valve, share authentication between web applications
+             Documentation at: /docs/config/valve.html -->
+        <!--
+        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
+        -->
+
+        <!-- Access log processes all example.
+             Documentation at: /docs/config/valve.html
+             Note: The pattern used is equivalent to using pattern="common" -->
+        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
+               prefix="localhost_access_log" suffix=".txt"
+               pattern="%h %l %u %t &quot;%r&quot; %s %b" />
+
+      </Host>
+    </Engine>
+  </Service>
+</Server>
diff --git a/tomee/tomee-security/src/test/resources/conf/tomcat-users.xml b/tomee/tomee-security/src/test/resources/conf/tomcat-users.xml
new file mode 100644
index 0000000..f7da309
--- /dev/null
+++ b/tomee/tomee-security/src/test/resources/conf/tomcat-users.xml
@@ -0,0 +1,19 @@
+<!--
+  ~ 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.
+  -->
+<tomcat-users>
+  <user name="tomcat" password="tomcat" roles="tomcat"/>
+</tomcat-users>


[tomee] 24/48: TOMEE-2365 - Test servlet without authentication.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit a465769f13d2426948fc72d6a84198a613fc9f89
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Wed Dec 26 18:59:38 2018 +0000

    TOMEE-2365 - Test servlet without authentication.
---
 .../org/apache/tomee/security/http/TomEEHttpMessageContext.java   | 3 ++-
 .../java/org/apache/tomee/security/servlet/SimpleServletTest.java | 8 +-------
 2 files changed, 3 insertions(+), 8 deletions(-)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/TomEEHttpMessageContext.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/TomEEHttpMessageContext.java
index 878a550..48a3272 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/TomEEHttpMessageContext.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/TomEEHttpMessageContext.java
@@ -36,6 +36,7 @@ import java.io.IOException;
 import java.security.Principal;
 import java.util.Set;
 
+import static javax.security.enterprise.AuthenticationStatus.NOT_DONE;
 import static javax.security.enterprise.AuthenticationStatus.SEND_FAILURE;
 import static javax.security.enterprise.AuthenticationStatus.SUCCESS;
 import static javax.security.enterprise.identitystore.CredentialValidationResult.Status.VALID;
@@ -193,7 +194,7 @@ public class TomEEHttpMessageContext implements HttpMessageContext {
 
     @Override
     public AuthenticationStatus doNothing() {
-        return null;
+        return NOT_DONE;
     }
 
     @Override
diff --git a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java
index ab33b9d..5d11cbc 100644
--- a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java
+++ b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java
@@ -20,13 +20,9 @@ import org.apache.openejb.loader.JarLocation;
 import org.apache.openejb.util.NetworkUtil;
 import org.apache.tomee.embedded.Configuration;
 import org.apache.tomee.embedded.Container;
-import org.apache.tomee.security.client.BasicAuthFilter;
 import org.junit.Test;
 
-import javax.security.enterprise.authentication.mechanism.http.BasicAuthenticationMechanismDefinition;
 import javax.servlet.ServletException;
-import javax.servlet.annotation.HttpConstraint;
-import javax.servlet.annotation.ServletSecurity;
 import javax.servlet.annotation.WebServlet;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
@@ -51,7 +47,7 @@ public class SimpleServletTest {
                         JarLocation.jarLocation(SimpleServletTest.class),
                         JarLocation.jarLocation(TomEESecurityServletContainerInitializer.class))) {
 
-            final Client client = ClientBuilder.newBuilder().register(new BasicAuthFilter()).build();
+            final Client client = ClientBuilder.newBuilder().build();
             final Response response =
                     client.target("http://localhost:" + container.getConfiguration().getHttpPort() + "/servlet")
                           .request()
@@ -61,8 +57,6 @@ public class SimpleServletTest {
     }
 
     @WebServlet(urlPatterns = "/servlet")
-    @ServletSecurity(@HttpConstraint(rolesAllowed = "tomcat"))
-    @BasicAuthenticationMechanismDefinition
     public static class TestServlet extends HttpServlet {
         @Override
         protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)


[tomee] 22/48: TOMEE-2365 - Fixed NPE on empty Authorization header.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit 8fa7252ee13de41f2ee1f3df97ade266d5ce786d
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Wed Dec 26 17:45:22 2018 +0000

    TOMEE-2365 - Fixed NPE on empty Authorization header.
---
 .../security/cdi/BasicAuthenticationMechanism.java | 10 ++-
 .../security/servlet/BasicAuthServletTest.java     | 76 ++++++++++++++++++++++
 2 files changed, 83 insertions(+), 3 deletions(-)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/BasicAuthenticationMechanism.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/BasicAuthenticationMechanism.java
index f4c4722..3bb5bea 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/BasicAuthenticationMechanism.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/BasicAuthenticationMechanism.java
@@ -28,6 +28,7 @@ import javax.security.enterprise.credential.BasicAuthenticationCredential;
 import javax.security.enterprise.identitystore.CredentialValidationResult;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
+import java.util.Optional;
 
 import static javax.security.enterprise.identitystore.CredentialValidationResult.Status.VALID;
 import static javax.ws.rs.core.HttpHeaders.AUTHORIZATION;
@@ -79,8 +80,11 @@ public class BasicAuthenticationMechanism implements HttpAuthenticationMechanism
     }
 
     private BasicAuthenticationCredential parseAuthenticationHeader(final String authenticationHeader) {
-        return !authenticationHeader.isEmpty() && authenticationHeader.startsWith("Basic ") ?
-               new BasicAuthenticationCredential(authenticationHeader.substring(6)) :
-               new BasicAuthenticationCredential(null);
+        return Optional.ofNullable(authenticationHeader)
+                       .filter(header -> !header.isEmpty())
+                       .filter(header -> header.startsWith("Basic "))
+                       .map(header -> header.substring(6))
+                       .map(BasicAuthenticationCredential::new)
+                       .orElseGet(() -> new BasicAuthenticationCredential(""));
     }
 }
diff --git a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/BasicAuthServletTest.java b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/BasicAuthServletTest.java
new file mode 100644
index 0000000..b25f169
--- /dev/null
+++ b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/BasicAuthServletTest.java
@@ -0,0 +1,76 @@
+/*
+ * 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.tomee.security.servlet;
+
+import org.apache.openejb.loader.JarLocation;
+import org.apache.openejb.util.NetworkUtil;
+import org.apache.tomee.embedded.Configuration;
+import org.apache.tomee.embedded.Container;
+import org.apache.tomee.security.client.BasicAuthFilter;
+import org.junit.Test;
+
+import javax.security.enterprise.authentication.mechanism.http.BasicAuthenticationMechanismDefinition;
+import javax.servlet.ServletException;
+import javax.servlet.annotation.HttpConstraint;
+import javax.servlet.annotation.ServletSecurity;
+import javax.servlet.annotation.WebServlet;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.client.ClientBuilder;
+import java.io.IOException;
+
+import static org.junit.Assert.assertEquals;
+
+public class BasicAuthServletTest {
+    @Test
+    public void testWebApp() throws Exception {
+        try (Container container = new Container(
+                new Configuration()
+                        .conf("conf")
+                        .http(NetworkUtil.getNextAvailablePort())
+                        .property("openejb.container.additional.exclude", "org.apache.tomee.security.")
+                        .property("openejb.additional.include", "tomee-"))
+                .deployPathsAsWebapp(
+                        JarLocation.jarLocation(SimpleServletTest.class),
+                        JarLocation.jarLocation(TomEESecurityServletContainerInitializer.class))) {
+
+            final String servlet = "http://localhost:" + container.getConfiguration().getHttpPort() + "/basic";
+
+            assertEquals(401, ClientBuilder.newBuilder().build()
+                                           .target(servlet)
+                                           .request()
+                                           .get().getStatus());
+
+            assertEquals(200, ClientBuilder.newBuilder().register(new BasicAuthFilter()).build()
+                                   .target(servlet)
+                                   .request()
+                                   .get().getStatus());
+        }
+    }
+
+    @WebServlet(urlPatterns = "/basic")
+    @ServletSecurity(@HttpConstraint(rolesAllowed = "tomcat"))
+    @BasicAuthenticationMechanismDefinition
+    public static class TestServlet extends HttpServlet {
+        @Override
+        protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
+                throws ServletException, IOException {
+            resp.getWriter().write("ok!");
+        }
+    }
+}


[tomee] 16/48: TOMEE-2365 - Fixed Basic header parsing.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit 8f15bd32eff87b6deadd8b5be7ccd3ec0e7e74c4
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Wed Dec 26 16:13:20 2018 +0000

    TOMEE-2365 - Fixed Basic header parsing.
---
 .../apache/tomee/security/cdi/BasicAuthenticationMechanism.java   | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/BasicAuthenticationMechanism.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/BasicAuthenticationMechanism.java
index ba7adbd..f4c4722 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/BasicAuthenticationMechanism.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/BasicAuthenticationMechanism.java
@@ -49,7 +49,7 @@ public class BasicAuthenticationMechanism implements HttpAuthenticationMechanism
 
         try {
             final CredentialValidationResult result =
-                    identityStoreHandler.validate(new BasicAuthenticationCredential(request.getHeader(AUTHORIZATION)));
+                    identityStoreHandler.validate(parseAuthenticationHeader(request.getHeader(AUTHORIZATION)));
 
             if (result.getStatus().equals(VALID)) {
                 return httpMessageContext.notifyContainerAboutLogin(result);
@@ -77,4 +77,10 @@ public class BasicAuthenticationMechanism implements HttpAuthenticationMechanism
                              final HttpMessageContext httpMessageContext) {
 
     }
+
+    private BasicAuthenticationCredential parseAuthenticationHeader(final String authenticationHeader) {
+        return !authenticationHeader.isEmpty() && authenticationHeader.startsWith("Basic ") ?
+               new BasicAuthenticationCredential(authenticationHeader.substring(6)) :
+               new BasicAuthenticationCredential(null);
+    }
 }


[tomee] 03/48: TOMEE-2365 - Replaced ApplicationComposer with TomEE Embedded.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit 7dad419d2c47817f0491cf41131291468ab0ad18
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Fri Dec 14 23:06:19 2018 +0000

    TOMEE-2365 - Replaced ApplicationComposer with TomEE Embedded.
---
 tomee/tomee-security/pom.xml                       | 10 ++---
 .../tomee/security/servlet/SimpleServletTest.java  | 49 +++++++---------------
 2 files changed, 19 insertions(+), 40 deletions(-)

diff --git a/tomee/tomee-security/pom.xml b/tomee/tomee-security/pom.xml
index d7943de..09e19f3 100644
--- a/tomee/tomee-security/pom.xml
+++ b/tomee/tomee-security/pom.xml
@@ -35,16 +35,14 @@
 
   <dependencies>
     <dependency>
-      <groupId>${project.groupId}</groupId>
+      <groupId>org.apache.tomee</groupId>
       <artifactId>javaee-api</artifactId>
     </dependency>
     <dependency>
       <groupId>${project.groupId}</groupId>
-      <artifactId>openejb-server</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>${project.groupId}</groupId>
-      <artifactId>openejb-http</artifactId>
+      <artifactId>tomee-embedded</artifactId>
+      <version>${project.version}</version>
+      <scope>test</scope>
     </dependency>
   </dependencies>
 </project>
diff --git a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java
index 08e3c6d..a9eabcb 100644
--- a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java
+++ b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java
@@ -16,18 +16,12 @@
  */
 package org.apache.tomee.security.servlet;
 
-import org.apache.openejb.jee.WebApp;
-import org.apache.openejb.junit.ApplicationComposer;
 import org.apache.openejb.loader.IO;
-import org.apache.openejb.testing.Classes;
-import org.apache.openejb.testing.Configuration;
-import org.apache.openejb.testing.EnableServices;
-import org.apache.openejb.testing.Module;
-import org.apache.openejb.testng.PropertiesBuilder;
+import org.apache.openejb.loader.JarLocation;
 import org.apache.openejb.util.NetworkUtil;
-import org.junit.BeforeClass;
+import org.apache.tomee.embedded.Configuration;
+import org.apache.tomee.embedded.Container;
 import org.junit.Test;
-import org.junit.runner.RunWith;
 
 import javax.servlet.ServletException;
 import javax.servlet.annotation.WebServlet;
@@ -36,37 +30,25 @@ import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import java.io.IOException;
 import java.net.URL;
-import java.util.Properties;
 
 import static org.junit.Assert.assertEquals;
 
-@RunWith(ApplicationComposer.class)
-@EnableServices("http")
 public class SimpleServletTest {
-    private static int port = -1;
-
-    @BeforeClass
-    public static void beforeClass() {
-        port = NetworkUtil.getNextAvailablePort();
-    }
-
-    @Configuration
-    public Properties props() {
-        return new PropertiesBuilder().p("httpejbd.port", Integer.toString(port)).build();
-    }
-
-    @Module
-    @Classes(TestServlet.class)
-    public WebApp app() {
-        return new WebApp().contextRoot("/servlet");
-    }
-
     @Test
-    public void servlet() throws Exception {
-        assertEquals("ok!", IO.slurp(new URL("http://localhost:" + port + "/servlet/test")));
+    public void testWebApp() throws Exception {
+        try (Container container = new Container(
+                new Configuration()
+                        .http(NetworkUtil.getNextAvailablePort())
+                        .property("openejb.container.additional.exclude", "org.apache.tomee.security.")
+                        .property("openejb.additional.include", "tomee-"))
+                .deployPathsAsWebapp(JarLocation.jarLocation(SimpleServletTest.class))) {
+
+            assertEquals("ok!", IO.slurp(
+                    new URL("http://localhost:" + container.getConfiguration().getHttpPort() + "/servlet")));
+        }
     }
 
-    @WebServlet(urlPatterns = "/test")
+    @WebServlet(urlPatterns = "/servlet")
     public static class TestServlet extends HttpServlet {
         @Override
         protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
@@ -74,5 +56,4 @@ public class SimpleServletTest {
             resp.getWriter().write("ok!");
         }
     }
-
 }


[tomee] 38/48: TOMEE-2365 - Removed unneeded methods.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit ab0eb4c8491df1393c99b38ab0b1f9386462b5d3
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Fri Dec 28 17:07:25 2018 +0000

    TOMEE-2365 - Removed unneeded methods.
---
 .../security/cdi/BasicAuthenticationMechanism.java   | 20 ++------------------
 .../security/cdi/DefaultAuthenticationMechanism.java | 13 -------------
 .../security/cdi/FormAuthenticationMechanism.java    | 13 -------------
 3 files changed, 2 insertions(+), 44 deletions(-)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/BasicAuthenticationMechanism.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/BasicAuthenticationMechanism.java
index 3bb5bea..8b86323 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/BasicAuthenticationMechanism.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/BasicAuthenticationMechanism.java
@@ -16,8 +16,6 @@
  */
 package org.apache.tomee.security.cdi;
 
-import org.apache.tomee.security.identitystore.TomEEIdentityStoreHandler;
-
 import javax.enterprise.context.ApplicationScoped;
 import javax.inject.Inject;
 import javax.security.enterprise.AuthenticationException;
@@ -26,6 +24,7 @@ import javax.security.enterprise.authentication.mechanism.http.HttpAuthenticatio
 import javax.security.enterprise.authentication.mechanism.http.HttpMessageContext;
 import javax.security.enterprise.credential.BasicAuthenticationCredential;
 import javax.security.enterprise.identitystore.CredentialValidationResult;
+import javax.security.enterprise.identitystore.IdentityStoreHandler;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import java.util.Optional;
@@ -36,7 +35,7 @@ import static javax.ws.rs.core.HttpHeaders.AUTHORIZATION;
 @ApplicationScoped
 public class BasicAuthenticationMechanism implements HttpAuthenticationMechanism {
     @Inject
-    private TomEEIdentityStoreHandler identityStoreHandler;
+    private IdentityStoreHandler identityStoreHandler;
 
     @Override
     public AuthenticationStatus validateRequest(final HttpServletRequest request,
@@ -64,21 +63,6 @@ public class BasicAuthenticationMechanism implements HttpAuthenticationMechanism
         return httpMessageContext.responseUnauthorized();
     }
 
-    @Override
-    public AuthenticationStatus secureResponse(final HttpServletRequest request,
-                                               final HttpServletResponse response,
-                                               final HttpMessageContext httpMessageContext)
-            throws AuthenticationException {
-        return null;
-    }
-
-    @Override
-    public void cleanSubject(final HttpServletRequest request,
-                             final HttpServletResponse response,
-                             final HttpMessageContext httpMessageContext) {
-
-    }
-
     private BasicAuthenticationCredential parseAuthenticationHeader(final String authenticationHeader) {
         return Optional.ofNullable(authenticationHeader)
                        .filter(header -> !header.isEmpty())
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/DefaultAuthenticationMechanism.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/DefaultAuthenticationMechanism.java
index 54bb000..cd18a17 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/DefaultAuthenticationMechanism.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/DefaultAuthenticationMechanism.java
@@ -64,18 +64,5 @@ public class DefaultAuthenticationMechanism implements HttpAuthenticationMechani
                 throws AuthenticationException {
             return httpMessageContext.doNothing();
         }
-
-        @Override
-        public AuthenticationStatus secureResponse(final HttpServletRequest request, final HttpServletResponse response,
-                                                   final HttpMessageContext httpMessageContext)
-                throws AuthenticationException {
-            return httpMessageContext.doNothing();
-        }
-
-        @Override
-        public void cleanSubject(final HttpServletRequest request, final HttpServletResponse response,
-                                 final HttpMessageContext httpMessageContext) {
-
-        }
     }
 }
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/FormAuthenticationMechanism.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/FormAuthenticationMechanism.java
index f60e7ea..08f482b 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/FormAuthenticationMechanism.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/FormAuthenticationMechanism.java
@@ -56,19 +56,6 @@ public class FormAuthenticationMechanism implements HttpAuthenticationMechanism,
         return httpMessageContext.doNothing();
     }
 
-    @Override
-    public AuthenticationStatus secureResponse(final HttpServletRequest request, final HttpServletResponse response,
-                                               final HttpMessageContext httpMessageContext)
-            throws AuthenticationException {
-        throw new UnsupportedOperationException();
-    }
-
-    @Override
-    public void cleanSubject(final HttpServletRequest request, final HttpServletResponse response,
-                             final HttpMessageContext httpMessageContext) {
-        throw new UnsupportedOperationException();
-    }
-
     public LoginToContinue getLoginToContinue() {
         return loginToContinue.get();
     }


[tomee] 34/48: TOMEE-2365 - Perform authentication on the second step of the form.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit c5c8a3e78ffd64edbd721223cc250b46fd6e1b6f
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Fri Dec 28 13:10:59 2018 +0000

    TOMEE-2365 - Perform authentication on the second step of the form.
---
 .../security/cdi/LoginToContinueInterceptor.java   |  41 ++++-
 .../security/http/LoginToContinueMechanism.java    |  48 +++++-
 .../tomee/security/http/SavedAuthentication.java   |  41 +++++
 .../apache/tomee/security/http/SavedRequest.java   | 178 +++++++++++++++++++++
 .../security/http/TomEEHttpMessageContext.java     |  12 +-
 5 files changed, 311 insertions(+), 9 deletions(-)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/LoginToContinueInterceptor.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/LoginToContinueInterceptor.java
index 1895689..1e0b0f3 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/LoginToContinueInterceptor.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/LoginToContinueInterceptor.java
@@ -17,6 +17,7 @@
 package org.apache.tomee.security.cdi;
 
 import org.apache.tomee.security.http.LoginToContinueMechanism;
+import org.apache.tomee.security.http.SavedRequest;
 
 import javax.annotation.Priority;
 import javax.interceptor.AroundInvoke;
@@ -30,7 +31,13 @@ import javax.servlet.http.HttpServletResponse;
 import java.util.Arrays;
 
 import static javax.interceptor.Interceptor.Priority.PLATFORM_BEFORE;
-import static org.apache.tomee.security.http.LoginToContinueMechanism.isOriginalRequestInSession;
+import static javax.security.enterprise.AuthenticationStatus.SEND_FAILURE;
+import static javax.security.enterprise.AuthenticationStatus.SUCCESS;
+import static org.apache.tomee.security.http.LoginToContinueMechanism.getRequest;
+import static org.apache.tomee.security.http.LoginToContinueMechanism.hasAuthentication;
+import static org.apache.tomee.security.http.LoginToContinueMechanism.hasRequest;
+import static org.apache.tomee.security.http.LoginToContinueMechanism.matchRequest;
+import static org.apache.tomee.security.http.LoginToContinueMechanism.saveAuthentication;
 import static org.apache.tomee.security.http.LoginToContinueMechanism.saveRequest;
 
 @LoginToContinue
@@ -90,7 +97,33 @@ public class LoginToContinueInterceptor {
         }
 
         if (isOnLoginPostback(httpMessageContext)) {
-            return null;
+            final AuthenticationStatus authenticationStatus = (AuthenticationStatus) invocationContext.proceed();
+
+            if (authenticationStatus.equals(SUCCESS)) {
+                if (httpMessageContext.getCallerPrincipal() == null) {
+                    return SUCCESS;
+                }
+
+                if (matchRequest(httpMessageContext.getRequest())) {
+                    return SUCCESS;
+                }
+
+                saveAuthentication(httpMessageContext.getRequest(),
+                                   httpMessageContext.getCallerPrincipal(),
+                                   httpMessageContext.getGroups());
+
+                final SavedRequest savedRequest = getRequest(httpMessageContext.getRequest());
+                return httpMessageContext.redirect(savedRequest.getRequestURLWithQueryString());
+            }
+
+            if (authenticationStatus.equals(SEND_FAILURE)) {
+                final LoginToContinue loginToContinue = getLoginToContinue(invocationContext);
+                if (!loginToContinue.errorPage().isEmpty()) {
+                    return httpMessageContext.forward(loginToContinue.errorPage());
+                }
+
+                return authenticationStatus;
+            }
         }
 
         if (isOnOriginalURLAfterAuthenticate(httpMessageContext)) {
@@ -101,11 +134,11 @@ public class LoginToContinueInterceptor {
     }
 
     private boolean isOnInitialProtectedURL(final HttpMessageContext httpMessageContext) {
-        return httpMessageContext.isProtected() && !isOriginalRequestInSession(httpMessageContext.getRequest());
+        return httpMessageContext.isProtected() && !hasRequest(httpMessageContext.getRequest());
     }
 
     private boolean isOnLoginPostback(final HttpMessageContext httpMessageContext) {
-        return false;
+        return hasRequest(httpMessageContext.getRequest()) && !hasAuthentication(httpMessageContext.getRequest());
     }
 
     private boolean isOnOriginalURLAfterAuthenticate(final HttpMessageContext httpMessageContext) {
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/LoginToContinueMechanism.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/LoginToContinueMechanism.java
index 482bae6..e67b4b4 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/LoginToContinueMechanism.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/LoginToContinueMechanism.java
@@ -16,21 +16,24 @@
  */
 package org.apache.tomee.security.http;
 
-import org.apache.catalina.authenticator.SavedRequest;
 import org.apache.tomcat.util.buf.ByteChunk;
 
 import javax.security.enterprise.authentication.mechanism.http.LoginToContinue;
 import javax.servlet.http.Cookie;
 import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
 import java.io.IOException;
 import java.io.InputStream;
+import java.security.Principal;
 import java.util.Enumeration;
 import java.util.Locale;
+import java.util.Set;
 
 public interface LoginToContinueMechanism {
     int MAX_SAVE_POST_SIZE = 4 * 1024;
 
     String ORIGINAL_REQUEST = "org.apache.tomee.security.request.original";
+    String AUTHENTICATION = "org.apache.tomee.security.request.authentication";
 
     LoginToContinue getLoginToContinue();
 
@@ -80,12 +83,53 @@ public interface LoginToContinueMechanism {
         saved.setMethod(request.getMethod());
         saved.setQueryString(request.getQueryString());
         saved.setRequestURI(request.getRequestURI());
+        saved.setRequestURL(request.getRequestURL().toString());
 
         // Stash the SavedRequest in our session for later use
         request.getSession().setAttribute(ORIGINAL_REQUEST, saved);
     }
 
-    static boolean isOriginalRequestInSession(final HttpServletRequest request) {
+    static boolean matchRequest(final HttpServletRequest request) {
+        // Has a session been created?
+        final HttpSession session = request.getSession(false);
+        if (session == null) {
+            return false;
+        }
+
+        // Is there a saved request?
+        final SavedRequest originalRequest = (SavedRequest) request.getSession().getAttribute(ORIGINAL_REQUEST);
+        if (originalRequest == null) {
+            return false;
+        }
+
+        // Is there a saved principal?
+        /*
+        if (session.getNote(Constants.FORM_PRINCIPAL_NOTE) == null) {
+            return false;
+        }
+        */
+
+        // Does the request URI match?
+        final String requestURI = request.getRequestURI();
+        return requestURI != null && requestURI.equals(originalRequest.getRequestURI());
+    }
+
+    static boolean hasRequest(final HttpServletRequest request) {
         return request.getSession().getAttribute(ORIGINAL_REQUEST) != null;
     }
+
+    static SavedRequest getRequest(final HttpServletRequest request) {
+        return (SavedRequest) request.getSession().getAttribute(ORIGINAL_REQUEST);
+    }
+
+    static void saveAuthentication(final HttpServletRequest request,
+                                   final Principal principal,
+                                   final Set<String> groups) {
+        final SavedAuthentication savedAuthentication = new SavedAuthentication(principal, groups);
+        request.getSession().setAttribute(AUTHENTICATION, savedAuthentication);
+    }
+
+    static boolean hasAuthentication(final HttpServletRequest request) {
+        return request.getSession().getAttribute(AUTHENTICATION) != null;
+    }
 }
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/SavedAuthentication.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/SavedAuthentication.java
new file mode 100644
index 0000000..5c30353
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/SavedAuthentication.java
@@ -0,0 +1,41 @@
+/*
+ * 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.tomee.security.http;
+
+
+import java.security.Principal;
+import java.util.Set;
+
+import static java.util.Collections.unmodifiableSet;
+
+public final class SavedAuthentication {
+    private final Principal principal;
+    private final Set<String> groups;
+
+    SavedAuthentication(final Principal principal, final Set<String> groups) {
+        this.principal = principal;
+        this.groups = unmodifiableSet(groups);
+    }
+
+    public Principal getPrincipal() {
+        return principal;
+    }
+
+    public Set<String> getGroups() {
+        return groups;
+    }
+}
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/SavedRequest.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/SavedRequest.java
new file mode 100644
index 0000000..ca49c53
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/SavedRequest.java
@@ -0,0 +1,178 @@
+/*
+ * 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.tomee.security.http;
+
+import org.apache.tomcat.util.buf.ByteChunk;
+
+import javax.servlet.http.Cookie;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+/**
+ * Mostly copied from org.apache.catalina.authenticator.SavedRequest.
+ */
+public final class SavedRequest {
+
+    SavedRequest() {
+    }
+
+    /**
+     * The set of Cookies associated with this Request.
+     */
+    private final List<Cookie> cookies = new ArrayList<>();
+
+    public void addCookie(Cookie cookie) {
+        cookies.add(cookie);
+    }
+
+    public Iterator<Cookie> getCookies() {
+        return cookies.iterator();
+    }
+
+
+    /**
+     * The set of Headers associated with this Request.  Each key is a header
+     * name, while the value is a List containing one or more actual
+     * values for this header.  The values are returned as an Iterator when
+     * you ask for them.
+     */
+    private final Map<String, List<String>> headers = new HashMap<>();
+
+    public void addHeader(String name, String value) {
+        List<String> values = headers.get(name);
+        if (values == null) {
+            values = new ArrayList<>();
+            headers.put(name, values);
+        }
+        values.add(value);
+    }
+
+    public Iterator<String> getHeaderNames() {
+        return headers.keySet().iterator();
+    }
+
+    public Iterator<String> getHeaderValues(String name) {
+        List<String> values = headers.get(name);
+        if (values == null) { return Collections.emptyIterator(); } else { return values.iterator(); }
+    }
+
+
+    /**
+     * The set of Locales associated with this Request.
+     */
+    private final List<Locale> locales = new ArrayList<>();
+
+    public void addLocale(Locale locale) {
+        locales.add(locale);
+    }
+
+    public Iterator<Locale> getLocales() {
+        return locales.iterator();
+    }
+
+
+    /**
+     * The request method used on this Request.
+     */
+    private String method = null;
+
+    public String getMethod() {
+        return this.method;
+    }
+
+    public void setMethod(String method) {
+        this.method = method;
+    }
+
+
+    /**
+     * The query string associated with this Request.
+     */
+    private String queryString = null;
+
+    public String getQueryString() {
+        return this.queryString;
+    }
+
+    public void setQueryString(String queryString) {
+        this.queryString = queryString;
+    }
+
+
+    /**
+     * The request URI associated with this Request. See javax.servlet.http.HttpServletRequest#getRequestURI().
+     */
+    private String requestURI = null;
+
+    public String getRequestURI() {
+        return this.requestURI;
+    }
+
+    public void setRequestURI(String requestURI) {
+        this.requestURI = requestURI;
+    }
+
+
+    /**
+     * The decode request URL associated with this Request. See javax.servlet.http.HttpServletRequest#getRequestURL().
+     */
+    private String requestURL = null;
+
+    public String getRequestURL() {
+        return this.requestURL;
+    }
+
+    public void setRequestURL(String requestURL) {
+        this.requestURL = requestURL;
+    }
+
+
+    /**
+     * The body of this request.
+     */
+    private ByteChunk body = null;
+
+    public ByteChunk getBody() {
+        return this.body;
+    }
+
+    public void setBody(ByteChunk body) {
+        this.body = body;
+    }
+
+    /**
+     * The content type of the request, used if this is a POST.
+     */
+    private String contentType = null;
+
+    public String getContentType() {
+        return this.contentType;
+    }
+
+    public void setContentType(String contentType) {
+        this.contentType = contentType;
+    }
+
+    public String getRequestURLWithQueryString() {
+        return queryString == null || queryString.isEmpty() ? requestURL : requestURL + "?" + queryString;
+    }
+}
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/TomEEHttpMessageContext.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/TomEEHttpMessageContext.java
index 4c087da..d67d74d 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/TomEEHttpMessageContext.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/TomEEHttpMessageContext.java
@@ -50,6 +50,9 @@ public class TomEEHttpMessageContext implements HttpMessageContext {
     private final Subject clientSubject;
     private final Subject serviceSubject;
 
+    private Principal principal;
+    private Set<String> groups;
+
     private TomEEHttpMessageContext(
             final CallbackHandler handler,
             final MessageInfo messageInfo,
@@ -190,10 +193,13 @@ public class TomEEHttpMessageContext implements HttpMessageContext {
                     new CallerPrincipalCallback(clientSubject, principal),
                     new GroupPrincipalCallback(clientSubject, groups.toArray(new String[groups.size()]))
             });
-        } catch (IOException | UnsupportedCallbackException e) {
+        } catch (final IOException | UnsupportedCallbackException e) {
             e.printStackTrace();
         }
 
+        this.principal = principal;
+        this.groups = groups;
+
         return SUCCESS;
     }
 
@@ -213,11 +219,11 @@ public class TomEEHttpMessageContext implements HttpMessageContext {
 
     @Override
     public Principal getCallerPrincipal() {
-        return null;
+        return principal;
     }
 
     @Override
     public Set<String> getGroups() {
-        return null;
+        return groups;
     }
 }


[tomee] 04/48: TOMEE-2365 - Initial implementation classes with ServerAuthModule to support Security spec Authentication Mechanisms.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit a3e8dce0abc9e567852279b1a14a431dbf008cd9
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Fri Dec 14 23:32:29 2018 +0000

    TOMEE-2365 - Initial implementation classes with ServerAuthModule to support Security spec Authentication Mechanisms.
---
 .../provider/TomEESecurityAuthConfigProvider.java  | 44 ++++++++++++++++
 .../provider/TomEESecurityServerAuthConfig.java    | 58 ++++++++++++++++++++++
 .../provider/TomEESecurityServerAuthContext.java   | 51 +++++++++++++++++++
 .../provider/TomEESecurityServerAuthModule.java    | 57 +++++++++++++++++++++
 .../TomEESecurityServletContainerInitializer.java  | 34 +++++++++++++
 .../javax.servlet.ServletContainerInitializer      | 17 +++++++
 .../tomee/security/servlet/SimpleServletTest.java  |  4 +-
 7 files changed, 264 insertions(+), 1 deletion(-)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityAuthConfigProvider.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityAuthConfigProvider.java
new file mode 100644
index 0000000..6654089
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityAuthConfigProvider.java
@@ -0,0 +1,44 @@
+/*
+ * 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.tomee.security.provider;
+
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.message.AuthException;
+import javax.security.auth.message.config.AuthConfigProvider;
+import javax.security.auth.message.config.ClientAuthConfig;
+import javax.security.auth.message.config.ServerAuthConfig;
+
+public class TomEESecurityAuthConfigProvider implements AuthConfigProvider {
+    @Override
+    public ClientAuthConfig getClientAuthConfig(final String layer, final String appContext,
+                                                final CallbackHandler handler)
+            throws AuthException, SecurityException {
+        return null;
+    }
+
+    @Override
+    public ServerAuthConfig getServerAuthConfig(final String layer, final String appContext,
+                                                final CallbackHandler handler)
+            throws AuthException, SecurityException {
+        return new TomEESecurityServerAuthConfig();
+    }
+
+    @Override
+    public void refresh() {
+
+    }
+}
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityServerAuthConfig.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityServerAuthConfig.java
new file mode 100644
index 0000000..bee97ce
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityServerAuthConfig.java
@@ -0,0 +1,58 @@
+/*
+ * 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.tomee.security.provider;
+
+import javax.security.auth.Subject;
+import javax.security.auth.message.AuthException;
+import javax.security.auth.message.MessageInfo;
+import javax.security.auth.message.config.ServerAuthConfig;
+import javax.security.auth.message.config.ServerAuthContext;
+import java.util.Map;
+
+public class TomEESecurityServerAuthConfig implements ServerAuthConfig {
+    @Override
+    public ServerAuthContext getAuthContext(final String authContextID, final Subject serviceSubject,
+                                            final Map properties)
+            throws AuthException {
+        return new TomEESecurityServerAuthContext();
+    }
+
+    @Override
+    public String getAppContext() {
+        return null;
+    }
+
+    @Override
+    public String getAuthContextID(final MessageInfo messageInfo) throws IllegalArgumentException {
+        return null;
+    }
+
+    @Override
+    public String getMessageLayer() {
+        return null;
+    }
+
+    @Override
+    public boolean isProtected() {
+        return false;
+    }
+
+    @Override
+    public void refresh() {
+
+    }
+}
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityServerAuthContext.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityServerAuthContext.java
new file mode 100644
index 0000000..6161a9b
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityServerAuthContext.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.tomee.security.provider;
+
+import javax.security.auth.Subject;
+import javax.security.auth.message.AuthException;
+import javax.security.auth.message.AuthStatus;
+import javax.security.auth.message.MessageInfo;
+import javax.security.auth.message.config.ServerAuthContext;
+
+public class TomEESecurityServerAuthContext implements ServerAuthContext {
+    private TomEESecurityServerAuthModule serverAuthModule;
+
+    public TomEESecurityServerAuthContext() throws AuthException {
+        this.serverAuthModule = new TomEESecurityServerAuthModule();
+        this.serverAuthModule.initialize(null, null, null, null);
+    }
+
+    @Override
+    public void cleanSubject(final MessageInfo messageInfo, final Subject subject)
+            throws AuthException {
+        serverAuthModule.cleanSubject(messageInfo, subject);
+    }
+
+    @Override
+    public AuthStatus secureResponse(final MessageInfo messageInfo, final Subject serviceSubject)
+            throws AuthException {
+        return serverAuthModule.secureResponse(messageInfo, serviceSubject);
+    }
+
+    @Override
+    public AuthStatus validateRequest(final MessageInfo messageInfo, final Subject clientSubject,
+                                      final Subject serviceSubject)
+            throws AuthException {
+        return serverAuthModule.validateRequest(messageInfo, clientSubject, serviceSubject);
+    }
+}
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityServerAuthModule.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityServerAuthModule.java
new file mode 100644
index 0000000..03418b4
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityServerAuthModule.java
@@ -0,0 +1,57 @@
+/*
+ * 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.tomee.security.provider;
+
+import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.message.AuthException;
+import javax.security.auth.message.AuthStatus;
+import javax.security.auth.message.MessageInfo;
+import javax.security.auth.message.MessagePolicy;
+import javax.security.auth.message.module.ServerAuthModule;
+import java.util.Map;
+
+public class TomEESecurityServerAuthModule implements ServerAuthModule {
+    @Override
+    public Class[] getSupportedMessageTypes() {
+        return new Class[0];
+    }
+
+    @Override
+    public void initialize(final MessagePolicy requestPolicy, final MessagePolicy responsePolicy,
+                           final CallbackHandler handler,
+                           final Map options) throws AuthException {
+
+    }
+
+    @Override
+    public void cleanSubject(final MessageInfo messageInfo, final Subject subject) throws AuthException {
+
+    }
+
+    @Override
+    public AuthStatus secureResponse(final MessageInfo messageInfo, final Subject serviceSubject) throws AuthException {
+        return AuthStatus.SUCCESS;
+    }
+
+    @Override
+    public AuthStatus validateRequest(final MessageInfo messageInfo, final Subject clientSubject,
+                                      final Subject serviceSubject)
+            throws AuthException {
+        return AuthStatus.SUCCESS;
+    }
+}
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/servlet/TomEESecurityServletContainerInitializer.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/servlet/TomEESecurityServletContainerInitializer.java
new file mode 100644
index 0000000..fd49140
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/servlet/TomEESecurityServletContainerInitializer.java
@@ -0,0 +1,34 @@
+/*
+ * 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.tomee.security.servlet;
+
+import org.apache.tomee.security.provider.TomEESecurityAuthConfigProvider;
+
+import javax.security.auth.message.config.AuthConfigFactory;
+import javax.servlet.ServletContainerInitializer;
+import javax.servlet.ServletContext;
+import javax.servlet.ServletException;
+import java.util.Set;
+
+public class TomEESecurityServletContainerInitializer implements ServletContainerInitializer {
+    @Override
+    public void onStartup(final Set<Class<?>> c, final ServletContext ctx) throws ServletException {
+        AuthConfigFactory.getFactory()
+                         .registerConfigProvider(new TomEESecurityAuthConfigProvider(), null, null,
+                                                 "TomEE Security JSR-375");
+    }
+}
diff --git a/tomee/tomee-security/src/main/resources/META-INF/services/javax.servlet.ServletContainerInitializer b/tomee/tomee-security/src/main/resources/META-INF/services/javax.servlet.ServletContainerInitializer
new file mode 100644
index 0000000..b70f313
--- /dev/null
+++ b/tomee/tomee-security/src/main/resources/META-INF/services/javax.servlet.ServletContainerInitializer
@@ -0,0 +1,17 @@
+#
+# 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.
+#
+org.apache.tomee.security.servlet.TomEESecurityServletContainerInitializer
diff --git a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java
index a9eabcb..e645971 100644
--- a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java
+++ b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java
@@ -41,7 +41,9 @@ public class SimpleServletTest {
                         .http(NetworkUtil.getNextAvailablePort())
                         .property("openejb.container.additional.exclude", "org.apache.tomee.security.")
                         .property("openejb.additional.include", "tomee-"))
-                .deployPathsAsWebapp(JarLocation.jarLocation(SimpleServletTest.class))) {
+                .deployPathsAsWebapp(
+                        JarLocation.jarLocation(SimpleServletTest.class),
+                        JarLocation.jarLocation(TomEESecurityServletContainerInitializer.class))) {
 
             assertEquals("ok!", IO.slurp(
                     new URL("http://localhost:" + container.getConfiguration().getHttpPort() + "/servlet")));


[tomee] 10/48: TOMEE-2365 - CDI Extension to register AuthenticationMechanism if definitions are found.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit 5df4e8f70be6fae6d66654068adf708466c1de96
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Tue Dec 18 23:31:24 2018 +0000

    TOMEE-2365 - CDI Extension to register AuthenticationMechanism if definitions are found.
---
 .../security/cdi/BasicAuthenticationMechanism.java | 80 ++++++++++++++++++++++
 .../tomee/security/cdi/TomEESecurityExtension.java | 53 ++++++++++++++
 .../services/javax.enterprise.inject.spi.Extension | 33 +++++++++
 .../src/test/resources/META-INF/beans.xml          |  0
 4 files changed, 166 insertions(+)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/BasicAuthenticationMechanism.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/BasicAuthenticationMechanism.java
new file mode 100644
index 0000000..8f433fa
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/BasicAuthenticationMechanism.java
@@ -0,0 +1,80 @@
+/*
+ * 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.tomee.security.cdi;
+
+import org.apache.tomee.security.identitystore.TomEEIdentityStoreHandler;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.inject.Inject;
+import javax.security.enterprise.AuthenticationException;
+import javax.security.enterprise.AuthenticationStatus;
+import javax.security.enterprise.authentication.mechanism.http.HttpAuthenticationMechanism;
+import javax.security.enterprise.authentication.mechanism.http.HttpMessageContext;
+import javax.security.enterprise.credential.BasicAuthenticationCredential;
+import javax.security.enterprise.identitystore.CredentialValidationResult;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.core.HttpHeaders;
+
+import static javax.security.enterprise.identitystore.CredentialValidationResult.Status.VALID;
+
+@ApplicationScoped
+public class BasicAuthenticationMechanism implements HttpAuthenticationMechanism {
+    @Inject
+    private TomEEIdentityStoreHandler identityStoreHandler;
+
+    @Override
+    public AuthenticationStatus validateRequest(final HttpServletRequest request,
+                                                final HttpServletResponse response,
+                                                final HttpMessageContext httpMessageContext)
+            throws AuthenticationException {
+
+        if (!httpMessageContext.isProtected()) {
+            return httpMessageContext.doNothing();
+        }
+
+        try {
+            final CredentialValidationResult result =
+                    identityStoreHandler.validate(new BasicAuthenticationCredential(HttpHeaders.AUTHORIZATION));
+
+            if (result.getStatus().equals(VALID)) {
+                return httpMessageContext.notifyContainerAboutLogin(result);
+            }
+
+        } catch (final IllegalArgumentException | IllegalStateException e) {
+            // Something was sent in the header was not valid. Fallthrough to the authenticate challenge again.
+        }
+
+        response.setHeader("WWW-Authenticate", "Basic");
+        return httpMessageContext.responseUnauthorized();
+    }
+
+    @Override
+    public AuthenticationStatus secureResponse(final HttpServletRequest request,
+                                               final HttpServletResponse response,
+                                               final HttpMessageContext httpMessageContext)
+            throws AuthenticationException {
+        return null;
+    }
+
+    @Override
+    public void cleanSubject(final HttpServletRequest request,
+                             final HttpServletResponse response,
+                             final HttpMessageContext httpMessageContext) {
+
+    }
+}
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityExtension.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityExtension.java
new file mode 100644
index 0000000..2f7bf04
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityExtension.java
@@ -0,0 +1,53 @@
+/*
+ * 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.tomee.security.cdi;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.enterprise.event.Observes;
+import javax.enterprise.inject.Any;
+import javax.enterprise.inject.Default;
+import javax.enterprise.inject.spi.AfterBeanDiscovery;
+import javax.enterprise.inject.spi.AnnotatedType;
+import javax.enterprise.inject.spi.Extension;
+import javax.enterprise.inject.spi.ProcessAnnotatedType;
+import javax.security.enterprise.authentication.mechanism.http.BasicAuthenticationMechanismDefinition;
+import javax.security.enterprise.authentication.mechanism.http.HttpAuthenticationMechanism;
+import java.util.HashSet;
+import java.util.Set;
+
+public class TomEESecurityExtension implements Extension {
+    private final Set<AnnotatedType> basicAuthentication = new HashSet<>();
+
+    void processAuthenticationMechanismDefinitions(@Observes final ProcessAnnotatedType<?> processAnnotatedType) {
+        final AnnotatedType<?> annotatedType = processAnnotatedType.getAnnotatedType();
+        if (annotatedType.isAnnotationPresent(BasicAuthenticationMechanismDefinition.class)) {
+            basicAuthentication.add(annotatedType);
+        }
+    }
+
+    void registerAuthenticationMechanism(@Observes final AfterBeanDiscovery afterBeanDiscovery) {
+        if (!basicAuthentication.isEmpty()) {
+            afterBeanDiscovery.addBean()
+               .id(BasicAuthenticationMechanism.class.getName())
+               .beanClass(BasicAuthenticationMechanism.class)
+               .types(Object.class, HttpAuthenticationMechanism.class, BasicAuthenticationMechanism.class)
+               .qualifiers(Default.Literal.INSTANCE, Any.Literal.INSTANCE)
+               .scope(ApplicationScoped.class)
+               .createWith(creationalContext -> new BasicAuthenticationMechanism());
+        }
+    }
+}
diff --git a/tomee/tomee-security/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension b/tomee/tomee-security/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension
new file mode 100644
index 0000000..6fc07e8
--- /dev/null
+++ b/tomee/tomee-security/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension
@@ -0,0 +1,33 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+org.apache.tomee.security.cdi.TomEESecurityExtension
diff --git a/tomee/tomee-security/src/test/resources/META-INF/beans.xml b/tomee/tomee-security/src/test/resources/META-INF/beans.xml
new file mode 100644
index 0000000..e69de29


[tomee] 20/48: TOMEE-2365 - Implementation of validateRequest delegating to the proper CDI bean.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit 868ea32ddbfa09610eec82293c38ad73c72ba21b
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Wed Dec 26 16:18:08 2018 +0000

    TOMEE-2365 - Implementation of validateRequest delegating to the proper CDI bean.
---
 .../provider/TomEESecurityServerAuthModule.java    | 51 +++++++++++++++++++++-
 1 file changed, 50 insertions(+), 1 deletion(-)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityServerAuthModule.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityServerAuthModule.java
index 03418b4..720a405 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityServerAuthModule.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityServerAuthModule.java
@@ -16,6 +16,9 @@
  */
 package org.apache.tomee.security.provider;
 
+import org.apache.tomee.security.cdi.TomEESecurityServletAuthenticationMechanismMapper;
+
+import javax.enterprise.inject.spi.CDI;
 import javax.security.auth.Subject;
 import javax.security.auth.callback.CallbackHandler;
 import javax.security.auth.message.AuthException;
@@ -23,8 +26,15 @@ import javax.security.auth.message.AuthStatus;
 import javax.security.auth.message.MessageInfo;
 import javax.security.auth.message.MessagePolicy;
 import javax.security.auth.message.module.ServerAuthModule;
+import javax.security.enterprise.AuthenticationException;
+import javax.security.enterprise.AuthenticationStatus;
+import javax.security.enterprise.authentication.mechanism.http.HttpAuthenticationMechanism;
+import javax.security.enterprise.authentication.mechanism.http.HttpMessageContext;
+import javax.servlet.http.HttpServletRequest;
 import java.util.Map;
 
+import static org.apache.tomee.security.http.TomEEHttpMessageContext.httpMessageContext;
+
 public class TomEESecurityServerAuthModule implements ServerAuthModule {
     @Override
     public Class[] getSupportedMessageTypes() {
@@ -52,6 +62,45 @@ public class TomEESecurityServerAuthModule implements ServerAuthModule {
     public AuthStatus validateRequest(final MessageInfo messageInfo, final Subject clientSubject,
                                       final Subject serviceSubject)
             throws AuthException {
-        return AuthStatus.SUCCESS;
+
+        final HttpMessageContext httpMessageContext = httpMessageContext(messageInfo, clientSubject, serviceSubject);
+
+        final HttpServletRequest request = httpMessageContext.getRequest();
+        final String servletName = request.getHttpServletMapping().getServletName();
+        final HttpAuthenticationMechanism authenticationMechanism =
+                CDI.current()
+                   .select(TomEESecurityServletAuthenticationMechanismMapper.class)
+                   .get()
+                   .getCurrentAuthenticationMechanism(servletName);
+
+        final AuthenticationStatus authenticationStatus;
+        try {
+            authenticationStatus =
+                    authenticationMechanism.validateRequest(httpMessageContext.getRequest(),
+                                                            httpMessageContext.getResponse(),
+                                                            httpMessageContext);
+
+
+        } catch (final AuthenticationException e) {
+            final AuthException authException = new AuthException(e.getMessage());
+            authException.initCause(e);
+            throw authException;
+        }
+
+        return mapToAuthStatus(authenticationStatus);
+    }
+
+    private AuthStatus mapToAuthStatus(final AuthenticationStatus authenticationStatus) {
+        switch (authenticationStatus) {
+            case SUCCESS:
+            case NOT_DONE:
+                return AuthStatus.SUCCESS;
+            case SEND_FAILURE:
+                return AuthStatus.SEND_FAILURE;
+            case SEND_CONTINUE:
+                return AuthStatus.SEND_CONTINUE;
+            default:
+                throw new IllegalArgumentException();
+        }
     }
 }


[tomee] 32/48: TOMEE-2365 - Added HtmlUnit to test authentication form.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit f0c4fa76c729d021931be86661325a7d33618358
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Fri Dec 28 10:56:28 2018 +0000

    TOMEE-2365 - Added HtmlUnit to test authentication form.
---
 tomee/tomee-security/pom.xml                       | 11 +++++++
 .../security/servlet/FormAuthServletTest.java      | 37 ++++++++++++++++++----
 2 files changed, 41 insertions(+), 7 deletions(-)

diff --git a/tomee/tomee-security/pom.xml b/tomee/tomee-security/pom.xml
index a472bf6..d720e82 100644
--- a/tomee/tomee-security/pom.xml
+++ b/tomee/tomee-security/pom.xml
@@ -33,6 +33,11 @@
   <name>OpenEJB :: TomEE :: Security</name>
   <description>Implementation of Java EE Security JSR-375</description>
 
+  <properties>
+    <!-- Reset Jetty Version to not clash with HtmlUnit -->
+    <jetty.version/>
+  </properties>
+
   <dependencies>
     <dependency>
       <groupId>org.apache.tomee</groupId>
@@ -58,6 +63,12 @@
       <version>${project.version}</version>
       <scope>test</scope>
     </dependency>
+    <dependency>
+      <groupId>net.sourceforge.htmlunit</groupId>
+      <artifactId>htmlunit</artifactId>
+      <version>2.33</version>
+      <scope>test</scope>
+    </dependency>
   </dependencies>
 </project>
 
diff --git a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/FormAuthServletTest.java b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/FormAuthServletTest.java
index 9881c5f..f006388 100644
--- a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/FormAuthServletTest.java
+++ b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/FormAuthServletTest.java
@@ -16,6 +16,10 @@
  */
 package org.apache.tomee.security.servlet;
 
+import com.gargoylesoftware.htmlunit.Page;
+import com.gargoylesoftware.htmlunit.WebClient;
+import com.gargoylesoftware.htmlunit.html.HtmlForm;
+import com.gargoylesoftware.htmlunit.html.HtmlPage;
 import org.junit.Test;
 
 import javax.enterprise.context.ApplicationScoped;
@@ -28,7 +32,6 @@ import javax.servlet.annotation.WebServlet;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
-import javax.ws.rs.client.ClientBuilder;
 import java.io.IOException;
 
 import static org.junit.Assert.assertEquals;
@@ -36,11 +39,17 @@ import static org.junit.Assert.assertEquals;
 public class FormAuthServletTest extends AbstractTomEESecurityTest {
     @Test
     public void authenticate() throws Exception {
-        final String servlet = "http://localhost:" + container.getConfiguration().getHttpPort() + "/form";
-        assertEquals(200, ClientBuilder.newBuilder().build()
-                                       .target(servlet)
-                                       .request()
-                                       .get().getStatus());
+        final WebClient webClient = new WebClient();
+        final HtmlPage page =
+                webClient.getPage("http://localhost:" + container.getConfiguration().getHttpPort() + "/form");
+        assertEquals(200, page.getWebResponse().getStatusCode());
+
+        final HtmlForm login = page.getFormByName("login");
+        login.getInputByName("j_username").setValueAttribute("tomcat");
+        login.getInputByName("j_password").setValueAttribute("tomcat");
+
+        final HtmlPage submit = login.getInputByName("submit").click();
+        System.out.println("submit.toString() = " + submit.toString());
     }
 
     @ApplicationScoped
@@ -56,7 +65,21 @@ public class FormAuthServletTest extends AbstractTomEESecurityTest {
         @Override
         protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
                 throws ServletException, IOException {
-
+            final String loginPage =
+                    "<html>" +
+                    "<body>" +
+                    "  <h1>Login Page</h1>" +
+                    "  <form name=\"login\" method=post action=\"j_security_check\">\n" +
+                    "    <p>Username:</p>" +
+                    "    <input type=\"text\" name=\"j_username\">\n" +
+                    "    <p>Password:</p>" +
+                    "    <input type=\"password\" name=\"j_password\">\n" +
+                    "    <input type=\"submit\" name=\"submit\" value=\"Submit\">\n" +
+                    "    <input type=\"reset\" value=\"Reset\">" +
+                    "  </form>" +
+                    "</body>" +
+                    "</html>";
+            resp.getWriter().write(loginPage);
         }
     }
 


[tomee] 43/48: TOMEE-2365 - Moved AbstractTomEESecurityTest to the base package.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit cbc6f4204bb64a2ba9e97fdb991feb01e3e1b029
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Tue Jan 8 15:35:31 2019 +0000

    TOMEE-2365 - Moved AbstractTomEESecurityTest to the base package.
---
 .../tomee/security/{servlet => }/AbstractTomEESecurityTest.java  | 9 ++++++++-
 .../org/apache/tomee/security/servlet/BasicAuthServletTest.java  | 1 +
 .../org/apache/tomee/security/servlet/FormAuthServletTest.java   | 1 +
 .../org/apache/tomee/security/servlet/SimpleServletTest.java     | 1 +
 4 files changed, 11 insertions(+), 1 deletion(-)

diff --git a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/AbstractTomEESecurityTest.java b/tomee/tomee-security/src/test/java/org/apache/tomee/security/AbstractTomEESecurityTest.java
similarity index 89%
rename from tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/AbstractTomEESecurityTest.java
rename to tomee/tomee-security/src/test/java/org/apache/tomee/security/AbstractTomEESecurityTest.java
index 8999b2b..1b8e90b 100644
--- a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/AbstractTomEESecurityTest.java
+++ b/tomee/tomee-security/src/test/java/org/apache/tomee/security/AbstractTomEESecurityTest.java
@@ -14,13 +14,15 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.apache.tomee.security.servlet;
+package org.apache.tomee.security;
 
 import org.apache.openejb.loader.JarLocation;
 import org.apache.openejb.util.NetworkUtil;
 import org.apache.tomee.embedded.Configuration;
 import org.apache.tomee.embedded.Container;
+import org.apache.tomee.security.servlet.TomEESecurityServletContainerInitializer;
 import org.junit.AfterClass;
+import org.junit.Before;
 import org.junit.BeforeClass;
 
 public abstract class AbstractTomEESecurityTest {
@@ -44,6 +46,11 @@ public abstract class AbstractTomEESecurityTest {
         container.close();
     }
 
+    @Before
+    public void setUpBefore() throws Exception {
+        container.inject(this);
+    }
+
     protected String getAppUrl() {
         return "http://localhost:" + container.getConfiguration().getHttpPort();
     }
diff --git a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/BasicAuthServletTest.java b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/BasicAuthServletTest.java
index e45e387..03f0a38 100644
--- a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/BasicAuthServletTest.java
+++ b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/BasicAuthServletTest.java
@@ -16,6 +16,7 @@
  */
 package org.apache.tomee.security.servlet;
 
+import org.apache.tomee.security.AbstractTomEESecurityTest;
 import org.apache.tomee.security.client.BasicAuthFilter;
 import org.junit.Test;
 
diff --git a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/FormAuthServletTest.java b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/FormAuthServletTest.java
index 1fd6f7e..df81b39 100644
--- a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/FormAuthServletTest.java
+++ b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/FormAuthServletTest.java
@@ -20,6 +20,7 @@ import com.gargoylesoftware.htmlunit.Page;
 import com.gargoylesoftware.htmlunit.WebClient;
 import com.gargoylesoftware.htmlunit.html.HtmlForm;
 import com.gargoylesoftware.htmlunit.html.HtmlPage;
+import org.apache.tomee.security.AbstractTomEESecurityTest;
 import org.junit.Test;
 
 import javax.enterprise.context.ApplicationScoped;
diff --git a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java
index e45e2ed..60c45d2 100644
--- a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java
+++ b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java
@@ -16,6 +16,7 @@
  */
 package org.apache.tomee.security.servlet;
 
+import org.apache.tomee.security.AbstractTomEESecurityTest;
 import org.junit.Test;
 
 import javax.servlet.ServletException;


[tomee] 31/48: TOMEE-2365 - First step of FormAuthentication. Forward to login page.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit 73f975ba6fdbe9c3c93a4f93dd6de7d746013ecd
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Thu Dec 27 19:09:47 2018 +0000

    TOMEE-2365 - First step of FormAuthentication. Forward to login page.
---
 .../security/cdi/LoginToContinueInterceptor.java   | 34 +++++++++++++++++-----
 .../security/http/TomEEHttpMessageContext.java     | 20 +++++++++++--
 2 files changed, 44 insertions(+), 10 deletions(-)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/LoginToContinueInterceptor.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/LoginToContinueInterceptor.java
index 98c8417..d35be0a 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/LoginToContinueInterceptor.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/LoginToContinueInterceptor.java
@@ -16,6 +16,8 @@
  */
 package org.apache.tomee.security.cdi;
 
+import org.apache.tomee.security.http.LoginToContinueMechanism;
+
 import javax.annotation.Priority;
 import javax.interceptor.AroundInvoke;
 import javax.interceptor.Interceptor;
@@ -42,21 +44,22 @@ public class LoginToContinueInterceptor {
                     HttpServletResponse.class,
                     HttpMessageContext.class
             })) {
-            return validateRequest((HttpMessageContext) invocationContext.getParameters()[2]);
+            return validateRequest(invocationContext);
         }
 
         return invocationContext.proceed();
     }
 
-    private AuthenticationStatus validateRequest(final HttpMessageContext httpMessageContext)
+    private AuthenticationStatus validateRequest(final InvocationContext invocationContext)
             throws AuthenticationException {
 
+        final HttpMessageContext httpMessageContext = (HttpMessageContext) invocationContext.getParameters()[2];
         clearStaleState(httpMessageContext);
 
         if (httpMessageContext.getAuthParameters().isNewAuthentication()) {
             return processCallerInitiatedAuthentication(httpMessageContext);
         } else {
-            return processContainerInitiatedAuthentication(httpMessageContext);
+            return processContainerInitiatedAuthentication(invocationContext, httpMessageContext);
         }
     }
 
@@ -64,14 +67,23 @@ public class LoginToContinueInterceptor {
 
     }
 
-    private AuthenticationStatus processCallerInitiatedAuthentication(final HttpMessageContext httpMessageContext) {
+    private AuthenticationStatus processCallerInitiatedAuthentication(
+            final HttpMessageContext httpMessageContext) {
         return null;
     }
 
-    private AuthenticationStatus processContainerInitiatedAuthentication(final HttpMessageContext httpMessageContext) {
+    private AuthenticationStatus processContainerInitiatedAuthentication(
+            final InvocationContext invocationContext,
+            final HttpMessageContext httpMessageContext) {
 
         if (isOnInitialProtectedURL(httpMessageContext)) {
-            return null;
+            final LoginToContinue loginToContinue = getLoginToContinue(invocationContext);
+
+            if (loginToContinue.useForwardToLogin()) {
+                return httpMessageContext.forward(loginToContinue.loginPage());
+            } else {
+                return httpMessageContext.redirect(loginToContinue.loginPage());
+            }
         }
 
         if (isOnOnLoginPostback(httpMessageContext)) {
@@ -86,7 +98,7 @@ public class LoginToContinueInterceptor {
     }
 
     private boolean isOnInitialProtectedURL(final HttpMessageContext httpMessageContext) {
-        return false;
+        return httpMessageContext.isProtected();
     }
 
     private boolean isOnOnLoginPostback(final HttpMessageContext httpMessageContext) {
@@ -96,4 +108,12 @@ public class LoginToContinueInterceptor {
     private boolean isOnOriginalURLAfterAuthenticate(final HttpMessageContext httpMessageContext) {
         return false;
     }
+
+    private LoginToContinue getLoginToContinue(final InvocationContext invocationContext) {
+        if (invocationContext.getTarget() instanceof LoginToContinueMechanism) {
+            return ((LoginToContinueMechanism) invocationContext.getTarget()).getLoginToContinue();
+        }
+
+        throw new IllegalArgumentException();
+    }
 }
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/TomEEHttpMessageContext.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/TomEEHttpMessageContext.java
index 48a3272..4c087da 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/TomEEHttpMessageContext.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/TomEEHttpMessageContext.java
@@ -30,6 +30,7 @@ import javax.security.enterprise.CallerPrincipal;
 import javax.security.enterprise.authentication.mechanism.http.AuthenticationParameters;
 import javax.security.enterprise.authentication.mechanism.http.HttpMessageContext;
 import javax.security.enterprise.identitystore.CredentialValidationResult;
+import javax.servlet.ServletException;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import java.io.IOException;
@@ -37,6 +38,7 @@ import java.security.Principal;
 import java.util.Set;
 
 import static javax.security.enterprise.AuthenticationStatus.NOT_DONE;
+import static javax.security.enterprise.AuthenticationStatus.SEND_CONTINUE;
 import static javax.security.enterprise.AuthenticationStatus.SEND_FAILURE;
 import static javax.security.enterprise.AuthenticationStatus.SUCCESS;
 import static javax.security.enterprise.identitystore.CredentialValidationResult.Status.VALID;
@@ -94,7 +96,7 @@ public class TomEEHttpMessageContext implements HttpMessageContext {
 
     @Override
     public AuthenticationParameters getAuthParameters() {
-        return null;
+        return new AuthenticationParameters();
     }
 
     @Override
@@ -140,12 +142,24 @@ public class TomEEHttpMessageContext implements HttpMessageContext {
 
     @Override
     public AuthenticationStatus redirect(final String location) {
-        return null;
+        try {
+            getResponse().sendRedirect(location);
+        } catch (final IOException e) {
+            e.printStackTrace();
+        }
+
+        return SEND_CONTINUE;
     }
 
     @Override
     public AuthenticationStatus forward(final String path) {
-        return null;
+        try {
+            getRequest().getRequestDispatcher(path).forward(getRequest(), getResponse());
+        } catch (final ServletException | IOException e) {
+            e.printStackTrace();
+        }
+
+        return SEND_CONTINUE;
     }
 
     @Override


[tomee] 29/48: TOMEE-2365 - Skeleton implementation for the LoginToContinueInterceptor.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit fe9fab62bf197d6c66df1af15928397f26e5e2b6
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Thu Dec 27 16:56:34 2018 +0000

    TOMEE-2365 - Skeleton implementation for the LoginToContinueInterceptor.
---
 .../security/cdi/FormAuthenticationMechanism.java  |  2 +
 .../security/cdi/LoginToContinueInterceptor.java   | 99 ++++++++++++++++++++++
 .../tomee/security/cdi/TomEESecurityExtension.java |  2 +
 3 files changed, 103 insertions(+)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/FormAuthenticationMechanism.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/FormAuthenticationMechanism.java
index b7a29e8..316575e 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/FormAuthenticationMechanism.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/FormAuthenticationMechanism.java
@@ -21,10 +21,12 @@ import javax.security.enterprise.AuthenticationException;
 import javax.security.enterprise.AuthenticationStatus;
 import javax.security.enterprise.authentication.mechanism.http.HttpAuthenticationMechanism;
 import javax.security.enterprise.authentication.mechanism.http.HttpMessageContext;
+import javax.security.enterprise.authentication.mechanism.http.LoginToContinue;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
 @ApplicationScoped
+@LoginToContinue
 public class FormAuthenticationMechanism implements HttpAuthenticationMechanism {
     @Override
     public AuthenticationStatus validateRequest(final HttpServletRequest request, final HttpServletResponse response,
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/LoginToContinueInterceptor.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/LoginToContinueInterceptor.java
new file mode 100644
index 0000000..98c8417
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/LoginToContinueInterceptor.java
@@ -0,0 +1,99 @@
+/*
+ * 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.tomee.security.cdi;
+
+import javax.annotation.Priority;
+import javax.interceptor.AroundInvoke;
+import javax.interceptor.Interceptor;
+import javax.interceptor.InvocationContext;
+import javax.security.enterprise.AuthenticationException;
+import javax.security.enterprise.AuthenticationStatus;
+import javax.security.enterprise.authentication.mechanism.http.HttpMessageContext;
+import javax.security.enterprise.authentication.mechanism.http.LoginToContinue;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.util.Arrays;
+
+import static javax.interceptor.Interceptor.Priority.PLATFORM_BEFORE;
+
+@LoginToContinue
+@Interceptor
+@Priority(PLATFORM_BEFORE + 220)
+public class LoginToContinueInterceptor {
+    @AroundInvoke
+    public Object intercept(final InvocationContext invocationContext) throws Exception {
+        if (invocationContext.getMethod().getName().equals("validateRequest") &&
+            Arrays.equals(invocationContext.getMethod().getParameterTypes(), new Class<?>[]{
+                    HttpServletRequest.class,
+                    HttpServletResponse.class,
+                    HttpMessageContext.class
+            })) {
+            return validateRequest((HttpMessageContext) invocationContext.getParameters()[2]);
+        }
+
+        return invocationContext.proceed();
+    }
+
+    private AuthenticationStatus validateRequest(final HttpMessageContext httpMessageContext)
+            throws AuthenticationException {
+
+        clearStaleState(httpMessageContext);
+
+        if (httpMessageContext.getAuthParameters().isNewAuthentication()) {
+            return processCallerInitiatedAuthentication(httpMessageContext);
+        } else {
+            return processContainerInitiatedAuthentication(httpMessageContext);
+        }
+    }
+
+    private void clearStaleState(final HttpMessageContext httpMessageContext) {
+
+    }
+
+    private AuthenticationStatus processCallerInitiatedAuthentication(final HttpMessageContext httpMessageContext) {
+        return null;
+    }
+
+    private AuthenticationStatus processContainerInitiatedAuthentication(final HttpMessageContext httpMessageContext) {
+
+        if (isOnInitialProtectedURL(httpMessageContext)) {
+            return null;
+        }
+
+        if (isOnOnLoginPostback(httpMessageContext)) {
+            return null;
+        }
+
+        if (isOnOriginalURLAfterAuthenticate(httpMessageContext)) {
+            return null;
+        }
+
+        return null;
+    }
+
+    private boolean isOnInitialProtectedURL(final HttpMessageContext httpMessageContext) {
+        return false;
+    }
+
+    private boolean isOnOnLoginPostback(final HttpMessageContext httpMessageContext) {
+        return false;
+    }
+
+    private boolean isOnOriginalURLAfterAuthenticate(final HttpMessageContext httpMessageContext) {
+        return false;
+    }
+}
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityExtension.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityExtension.java
index 91036c9..f0214d1 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityExtension.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityExtension.java
@@ -49,6 +49,8 @@ public class TomEESecurityExtension implements Extension {
                 beanManager.createAnnotatedType(TomEESecurityServletAuthenticationMechanismMapper.class));
         beforeBeanDiscovery.addAnnotatedType(beanManager.createAnnotatedType(TomEEDefaultIdentityStore.class));
         beforeBeanDiscovery.addAnnotatedType(beanManager.createAnnotatedType(TomEEIdentityStoreHandler.class));
+
+        beforeBeanDiscovery.addAnnotatedType(beanManager.createAnnotatedType(LoginToContinueInterceptor.class));
     }
 
     void processAuthenticationMechanismDefinitions(@Observes


[tomee] 08/48: TOMEE-2365 - Added credentials API for Basic Auth.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit cdd673a8c4f78daddaec6f5080acd13edabb5856
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Tue Dec 18 18:03:37 2018 +0000

    TOMEE-2365 - Added credentials API for Basic Auth.
---
 .../credential/AbstractClearableCredential.java    | 39 +++++++++++++
 .../credential/BasicAuthenticationCredential.java  | 67 ++++++++++++++++++++++
 .../security/enterprise/credential/Password.java   | 56 ++++++++++++++++++
 .../credential/UsernamePasswordCredential.java     | 54 +++++++++++++++++
 4 files changed, 216 insertions(+)

diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/credential/AbstractClearableCredential.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/credential/AbstractClearableCredential.java
new file mode 100644
index 0000000..8b9ac9c
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/credential/AbstractClearableCredential.java
@@ -0,0 +1,39 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package javax.security.enterprise.credential;
+
+public abstract class AbstractClearableCredential implements Credential {
+
+    private volatile boolean cleared = false;
+
+    @Override
+    public final boolean isCleared() {
+        return cleared;
+    }
+
+    protected final void setCleared() {
+        this.cleared = true;
+    }
+
+    @Override
+    public final void clear() {
+        clearCredential();
+        setCleared();
+    }
+
+    protected abstract void clearCredential();
+}
diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/credential/BasicAuthenticationCredential.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/credential/BasicAuthenticationCredential.java
new file mode 100644
index 0000000..404cc3c
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/credential/BasicAuthenticationCredential.java
@@ -0,0 +1,67 @@
+/*
+ * 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 javax.security.enterprise.credential;
+
+import java.io.UnsupportedEncodingException;
+import java.util.Base64;
+
+public class BasicAuthenticationCredential extends UsernamePasswordCredential {
+
+    public BasicAuthenticationCredential(String authorizationHeader) {
+        super(parseUsername(authorizationHeader), parsePassword(authorizationHeader));
+    }
+
+    private static String decodeHeader(String authorizationHeader) {
+        final String BASIC_AUTH_CHARSET = "US-ASCII";
+
+        if (null == authorizationHeader) {
+            throw new NullPointerException("authorization header");
+        }
+
+        if (authorizationHeader.isEmpty()) {
+            throw new IllegalArgumentException("authorization header is empty");
+        }
+
+        final Base64.Decoder decoder = Base64.getMimeDecoder();
+        byte[] decodedBytes = decoder.decode(authorizationHeader);
+        try {
+            return new String(decodedBytes, BASIC_AUTH_CHARSET);
+        } catch (UnsupportedEncodingException e) {
+            throw new IllegalStateException("Unknown Charset: " + BASIC_AUTH_CHARSET, e);
+        }
+    }
+
+    private static String parseUsername(String authorizationHeader) {
+        String decodedAuthorizationHeader = decodeHeader(authorizationHeader);
+        int delimiterIndex = decodedAuthorizationHeader.indexOf(':');
+        if (delimiterIndex > -1) {
+            return decodedAuthorizationHeader.substring(0, delimiterIndex);
+        } else {
+            return decodedAuthorizationHeader;
+        }
+    }
+
+    private static Password parsePassword(String authorizationHeader) {
+        String decodedAuthorizationHeader = decodeHeader(authorizationHeader);
+        int delimiterIndex = decodedAuthorizationHeader.indexOf(':');
+        if (delimiterIndex > -1) {
+            return new Password(decodedAuthorizationHeader.substring(delimiterIndex + 1));
+        } else {
+            return new Password("");
+        }
+    }
+}
diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/credential/Password.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/credential/Password.java
new file mode 100644
index 0000000..b52c429
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/credential/Password.java
@@ -0,0 +1,56 @@
+/*
+ * 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 javax.security.enterprise.credential;
+
+import java.util.Arrays;
+
+import static java.util.Arrays.copyOf;
+import static java.util.Objects.requireNonNull;
+
+public class Password {
+    private static final char[] EMPTY_VALUE = new char[0];
+    private volatile char[] value;
+
+    public Password(char[] value) {
+        requireNonNull(value, "Password value may not be null");
+
+        this.value = copyOf(value, value.length);
+    }
+
+    public Password(String value) {
+        this(null == value ? null : value.toCharArray());
+    }
+
+    public char[] getValue() {
+        return value;
+    }
+
+    public void clear() {
+        if (EMPTY_VALUE == value) { return; }
+
+        char[] tempValue = value;
+        value = EMPTY_VALUE;
+
+        for (int i = 0; i < tempValue.length; i++) {
+            tempValue[i] = 0x00;
+        }
+    }
+    
+    public boolean compareTo(String password) {
+        return password != null && Arrays.equals(password.toCharArray(), value);
+    }
+}
diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/credential/UsernamePasswordCredential.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/credential/UsernamePasswordCredential.java
new file mode 100644
index 0000000..6521397
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/credential/UsernamePasswordCredential.java
@@ -0,0 +1,54 @@
+/*
+ * 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 javax.security.enterprise.credential;
+
+public class UsernamePasswordCredential extends AbstractClearableCredential {
+
+    private final String caller;
+    private final Password password;
+
+    public UsernamePasswordCredential(String callerName, String password) {
+        this.caller = callerName;
+        this.password = new Password(password);
+    }
+
+    public UsernamePasswordCredential(String callerName, Password password) {
+        this.caller = callerName;
+        this.password = password;
+    }
+
+    public Password getPassword() {
+        return password;
+    }
+
+    public String getPasswordAsString() {
+        return String.valueOf(getPassword().getValue());
+    }
+
+    @Override
+    public void clearCredential() {
+        password.clear();
+    }
+
+    public String getCaller() {
+        return caller;
+    }
+
+    public boolean compareTo(String callerName, String password) {
+        return getCaller().equals(callerName) && getPassword().compareTo(password);
+    }
+}


[tomee] 21/48: TOMEE-2365 - Propagate CallbackHandler to perform authentication.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit a88d557937881238778ab81a6e79e62617cc2158
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Wed Dec 26 17:12:49 2018 +0000

    TOMEE-2365 - Propagate CallbackHandler to perform authentication.
---
 .../security/http/TomEEHttpMessageContext.java     | 40 ++++++++++++++++------
 .../provider/TomEESecurityAuthConfigProvider.java  |  2 +-
 .../provider/TomEESecurityServerAuthConfig.java    | 17 +++++++--
 .../provider/TomEESecurityServerAuthContext.java   |  5 +--
 .../provider/TomEESecurityServerAuthModule.java    |  7 ++--
 5 files changed, 52 insertions(+), 19 deletions(-)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/TomEEHttpMessageContext.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/TomEEHttpMessageContext.java
index dfb7627..878a550 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/TomEEHttpMessageContext.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/TomEEHttpMessageContext.java
@@ -19,8 +19,12 @@ package org.apache.tomee.security.http;
 import org.apache.catalina.authenticator.jaspic.MessageInfoImpl;
 
 import javax.security.auth.Subject;
+import javax.security.auth.callback.Callback;
 import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.UnsupportedCallbackException;
 import javax.security.auth.message.MessageInfo;
+import javax.security.auth.message.callback.CallerPrincipalCallback;
+import javax.security.auth.message.callback.GroupPrincipalCallback;
 import javax.security.enterprise.AuthenticationStatus;
 import javax.security.enterprise.CallerPrincipal;
 import javax.security.enterprise.authentication.mechanism.http.AuthenticationParameters;
@@ -38,22 +42,28 @@ import static javax.security.enterprise.identitystore.CredentialValidationResult
 import static javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED;
 
 public class TomEEHttpMessageContext implements HttpMessageContext {
+    private final CallbackHandler handler;
     private final MessageInfo messageInfo;
     private final Subject clientSubject;
     private final Subject serviceSubject;
 
-    private TomEEHttpMessageContext(final MessageInfo messageInfo,
-                                    final Subject clientSubject,
-                                    final Subject serviceSubject) {
+    private TomEEHttpMessageContext(
+            final CallbackHandler handler,
+            final MessageInfo messageInfo,
+            final Subject clientSubject,
+            final Subject serviceSubject) {
+        this.handler = handler;
         this.messageInfo = messageInfo;
         this.clientSubject = clientSubject;
         this.serviceSubject = serviceSubject;
     }
 
-    public static TomEEHttpMessageContext httpMessageContext(final MessageInfo messageInfo,
-                                                             final Subject clientSubject,
-                                                             final Subject serviceSubject) {
-        return new TomEEHttpMessageContext(messageInfo, clientSubject, serviceSubject);
+    public static TomEEHttpMessageContext httpMessageContext(
+            final CallbackHandler handler,
+            final MessageInfo messageInfo,
+            final Subject clientSubject,
+            final Subject serviceSubject) {
+        return new TomEEHttpMessageContext(handler, messageInfo, clientSubject, serviceSubject);
     }
 
     @Override
@@ -88,17 +98,17 @@ public class TomEEHttpMessageContext implements HttpMessageContext {
 
     @Override
     public CallbackHandler getHandler() {
-        return null;
+        return handler;
     }
 
     @Override
     public MessageInfo getMessageInfo() {
-        return null;
+        return messageInfo;
     }
 
     @Override
     public Subject getClientSubject() {
-        return null;
+        return clientSubject;
     }
 
     @Override
@@ -159,7 +169,15 @@ public class TomEEHttpMessageContext implements HttpMessageContext {
 
     @Override
     public AuthenticationStatus notifyContainerAboutLogin(final Principal principal, final Set<String> groups) {
-        // Needs more stuff in here.
+
+        try {
+            handler.handle(new Callback[] {
+                    new CallerPrincipalCallback(clientSubject, principal),
+                    new GroupPrincipalCallback(clientSubject, groups.toArray(new String[groups.size()]))
+            });
+        } catch (IOException | UnsupportedCallbackException e) {
+            e.printStackTrace();
+        }
 
         return SUCCESS;
     }
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityAuthConfigProvider.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityAuthConfigProvider.java
index 6654089..c799598 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityAuthConfigProvider.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityAuthConfigProvider.java
@@ -34,7 +34,7 @@ public class TomEESecurityAuthConfigProvider implements AuthConfigProvider {
     public ServerAuthConfig getServerAuthConfig(final String layer, final String appContext,
                                                 final CallbackHandler handler)
             throws AuthException, SecurityException {
-        return new TomEESecurityServerAuthConfig();
+        return new TomEESecurityServerAuthConfig(layer, appContext, handler);
     }
 
     @Override
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityServerAuthConfig.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityServerAuthConfig.java
index bee97ce..5686b68 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityServerAuthConfig.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityServerAuthConfig.java
@@ -17,6 +17,7 @@
 package org.apache.tomee.security.provider;
 
 import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
 import javax.security.auth.message.AuthException;
 import javax.security.auth.message.MessageInfo;
 import javax.security.auth.message.config.ServerAuthConfig;
@@ -24,16 +25,26 @@ import javax.security.auth.message.config.ServerAuthContext;
 import java.util.Map;
 
 public class TomEESecurityServerAuthConfig implements ServerAuthConfig {
+    private String layer;
+    private String appContext;
+    private CallbackHandler handler;
+
+    public TomEESecurityServerAuthConfig(final String layer, final String appContext, final CallbackHandler handler) {
+        this.layer = layer;
+        this.appContext = appContext;
+        this.handler = handler;
+    }
+
     @Override
     public ServerAuthContext getAuthContext(final String authContextID, final Subject serviceSubject,
                                             final Map properties)
             throws AuthException {
-        return new TomEESecurityServerAuthContext();
+        return new TomEESecurityServerAuthContext(handler);
     }
 
     @Override
     public String getAppContext() {
-        return null;
+        return appContext;
     }
 
     @Override
@@ -43,7 +54,7 @@ public class TomEESecurityServerAuthConfig implements ServerAuthConfig {
 
     @Override
     public String getMessageLayer() {
-        return null;
+        return layer;
     }
 
     @Override
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityServerAuthContext.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityServerAuthContext.java
index 6161a9b..1f853cc 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityServerAuthContext.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityServerAuthContext.java
@@ -17,6 +17,7 @@
 package org.apache.tomee.security.provider;
 
 import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
 import javax.security.auth.message.AuthException;
 import javax.security.auth.message.AuthStatus;
 import javax.security.auth.message.MessageInfo;
@@ -25,9 +26,9 @@ import javax.security.auth.message.config.ServerAuthContext;
 public class TomEESecurityServerAuthContext implements ServerAuthContext {
     private TomEESecurityServerAuthModule serverAuthModule;
 
-    public TomEESecurityServerAuthContext() throws AuthException {
+    public TomEESecurityServerAuthContext(final CallbackHandler handler) throws AuthException {
         this.serverAuthModule = new TomEESecurityServerAuthModule();
-        this.serverAuthModule.initialize(null, null, null, null);
+        this.serverAuthModule.initialize(null, null, handler, null);
     }
 
     @Override
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityServerAuthModule.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityServerAuthModule.java
index 720a405..e884f0e 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityServerAuthModule.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/provider/TomEESecurityServerAuthModule.java
@@ -36,6 +36,8 @@ import java.util.Map;
 import static org.apache.tomee.security.http.TomEEHttpMessageContext.httpMessageContext;
 
 public class TomEESecurityServerAuthModule implements ServerAuthModule {
+    private CallbackHandler handler;
+
     @Override
     public Class[] getSupportedMessageTypes() {
         return new Class[0];
@@ -45,7 +47,7 @@ public class TomEESecurityServerAuthModule implements ServerAuthModule {
     public void initialize(final MessagePolicy requestPolicy, final MessagePolicy responsePolicy,
                            final CallbackHandler handler,
                            final Map options) throws AuthException {
-
+        this.handler = handler;
     }
 
     @Override
@@ -63,7 +65,8 @@ public class TomEESecurityServerAuthModule implements ServerAuthModule {
                                       final Subject serviceSubject)
             throws AuthException {
 
-        final HttpMessageContext httpMessageContext = httpMessageContext(messageInfo, clientSubject, serviceSubject);
+        final HttpMessageContext httpMessageContext =
+                httpMessageContext(handler, messageInfo, clientSubject, serviceSubject);
 
         final HttpServletRequest request = httpMessageContext.getRequest();
         final String servletName = request.getHttpServletMapping().getServletName();


[tomee] 30/48: TOMEE-2365 - Added way to inject LoginToContinue when required by the specific AuthenticationMechanism.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit f4b8c03e2261f1797a8bd920fcd98c52a2b56c97
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Thu Dec 27 18:08:37 2018 +0000

    TOMEE-2365 - Added way to inject LoginToContinue when required by the specific AuthenticationMechanism.
---
 .../security/cdi/FormAuthenticationMechanism.java  | 13 +++++++++++-
 .../tomee/security/cdi/TomEESecurityExtension.java | 21 ++++++++++++++++++++
 .../security/http/LoginToContinueMechanism.java    | 23 ++++++++++++++++++++++
 3 files changed, 56 insertions(+), 1 deletion(-)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/FormAuthenticationMechanism.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/FormAuthenticationMechanism.java
index 316575e..8846a7a 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/FormAuthenticationMechanism.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/FormAuthenticationMechanism.java
@@ -16,7 +16,10 @@
  */
 package org.apache.tomee.security.cdi;
 
+import org.apache.tomee.security.http.LoginToContinueMechanism;
+
 import javax.enterprise.context.ApplicationScoped;
+import javax.inject.Inject;
 import javax.security.enterprise.AuthenticationException;
 import javax.security.enterprise.AuthenticationStatus;
 import javax.security.enterprise.authentication.mechanism.http.HttpAuthenticationMechanism;
@@ -24,10 +27,14 @@ import javax.security.enterprise.authentication.mechanism.http.HttpMessageContex
 import javax.security.enterprise.authentication.mechanism.http.LoginToContinue;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
+import java.util.function.Supplier;
 
 @ApplicationScoped
 @LoginToContinue
-public class FormAuthenticationMechanism implements HttpAuthenticationMechanism {
+public class FormAuthenticationMechanism implements HttpAuthenticationMechanism, LoginToContinueMechanism {
+    @Inject
+    private Supplier<LoginToContinue> loginToContinue;
+
     @Override
     public AuthenticationStatus validateRequest(final HttpServletRequest request, final HttpServletResponse response,
                                                 final HttpMessageContext httpMessageContext)
@@ -47,4 +54,8 @@ public class FormAuthenticationMechanism implements HttpAuthenticationMechanism
                              final HttpMessageContext httpMessageContext) {
         throw new UnsupportedOperationException();
     }
+
+    public LoginToContinue getLoginToContinue() {
+        return loginToContinue.get();
+    }
 }
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityExtension.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityExtension.java
index f0214d1..2fb9ef5 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityExtension.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityExtension.java
@@ -32,11 +32,14 @@ import javax.enterprise.inject.spi.BeforeBeanDiscovery;
 import javax.enterprise.inject.spi.Extension;
 import javax.enterprise.inject.spi.ProcessAnnotatedType;
 import javax.enterprise.inject.spi.WithAnnotations;
+import javax.enterprise.util.TypeLiteral;
 import javax.security.enterprise.authentication.mechanism.http.BasicAuthenticationMechanismDefinition;
 import javax.security.enterprise.authentication.mechanism.http.FormAuthenticationMechanismDefinition;
 import javax.security.enterprise.authentication.mechanism.http.HttpAuthenticationMechanism;
+import javax.security.enterprise.authentication.mechanism.http.LoginToContinue;
 import java.util.HashSet;
 import java.util.Set;
+import java.util.function.Supplier;
 
 public class TomEESecurityExtension implements Extension {
     private final Set<AnnotatedType> basicAuthentication = new HashSet<>();
@@ -90,9 +93,20 @@ public class TomEESecurityExtension implements Extension {
                     });
         }
 
+        // TODO - Support multiple here
         if (!formAuthentication.isEmpty()) {
             afterBeanDiscovery
                     .addBean()
+                    .id(Supplier.class.getName() + "#" + LoginToContinue.class.getName())
+                    .beanClass(Supplier.class)
+                    .addType(Object.class)
+                    .addType(new TypeLiteral<Supplier<LoginToContinue>>() {})
+                    .qualifiers(Default.Literal.INSTANCE, Any.Literal.INSTANCE)
+                    .scope(ApplicationScoped.class)
+                    .createWith(creationalContext -> createLoginToContinueSupplier());
+
+            afterBeanDiscovery
+                    .addBean()
                     .id(FormAuthenticationMechanism.class.getName())
                     .beanClass(FormAuthenticationMechanism.class)
                     .types(Object.class, HttpAuthenticationMechanism.class, FormAuthenticationMechanism.class)
@@ -114,4 +128,11 @@ public class TomEESecurityExtension implements Extension {
     public boolean hasAuthenticationMechanisms() {
         return !basicAuthentication.isEmpty();
     }
+
+    private Supplier<LoginToContinue> createLoginToContinueSupplier() {
+        return () -> formAuthentication.iterator()
+                               .next()
+                               .getAnnotation(FormAuthenticationMechanismDefinition.class)
+                               .loginToContinue();
+    }
 }
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/LoginToContinueMechanism.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/LoginToContinueMechanism.java
new file mode 100644
index 0000000..fe5fccd
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/LoginToContinueMechanism.java
@@ -0,0 +1,23 @@
+/*
+ * 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.tomee.security.http;
+
+import javax.security.enterprise.authentication.mechanism.http.LoginToContinue;
+
+public interface LoginToContinueMechanism {
+    LoginToContinue getLoginToContinue();
+}


[tomee] 01/48: TOMEE-2365 - Added project for EE Security JSR-375 implementation.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit 6e37459b59c5e78d3cb838448e26f4b99ee60e57
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Thu Dec 13 22:51:06 2018 +0000

    TOMEE-2365 - Added project for EE Security JSR-375 implementation.
---
 tomee/pom.xml                |  1 +
 tomee/tomee-security/pom.xml | 44 ++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 45 insertions(+)

diff --git a/tomee/pom.xml b/tomee/pom.xml
index fc51282..af3c28f 100644
--- a/tomee/pom.xml
+++ b/tomee/pom.xml
@@ -54,6 +54,7 @@
     <module>tomee-juli</module>
     <module>tomee-overlay-runner</module>
     <!--<module>tomee-deb</module>-->
+    <module>tomee-security</module>
   </modules>
 
 
diff --git a/tomee/tomee-security/pom.xml b/tomee/tomee-security/pom.xml
new file mode 100644
index 0000000..064e5bb
--- /dev/null
+++ b/tomee/tomee-security/pom.xml
@@ -0,0 +1,44 @@
+<?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.
+-->
+
+<!-- $Rev: 600338 $ $Date: 2007-12-02 09:08:04 -0800 (Sun, 02 Dec 2007) $ -->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+  <parent>
+    <artifactId>tomee</artifactId>
+    <groupId>org.apache.tomee</groupId>
+    <version>8.0.0-SNAPSHOT</version>
+  </parent>
+
+  <modelVersion>4.0.0</modelVersion>
+  <artifactId>tomee-security</artifactId>
+  <packaging>jar</packaging>
+  <name>OpenEJB :: TomEE :: Security</name>
+  <description>Implementation of Java EE Security JSR-375</description>
+
+  <dependencies>
+    <dependency>
+      <groupId>${project.groupId}</groupId>
+      <artifactId>javaee-api</artifactId>
+      <classifier>tomcat</classifier>
+    </dependency>
+  </dependencies>
+</project>
+


[tomee] 45/48: TOMEE-2365 - Improved exception message on multiple HttpAuthenticationMechanism.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit e0eea232387cfdbc0c4ddc81c7a250dc38a6a3d8
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Tue Jan 8 18:54:07 2019 +0000

    TOMEE-2365 - Improved exception message on multiple HttpAuthenticationMechanism.
---
 .../TomEESecurityServletAuthenticationMechanismMapper.java    | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityServletAuthenticationMechanismMapper.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityServletAuthenticationMechanismMapper.java
index d054783..2f2979c 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityServletAuthenticationMechanismMapper.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityServletAuthenticationMechanismMapper.java
@@ -32,6 +32,9 @@ import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.stream.Collectors;
 
+import static java.util.stream.Collectors.toList;
+import static org.apache.commons.lang3.StringUtils.substringBefore;
+
 @ApplicationScoped
 public class TomEESecurityServletAuthenticationMechanismMapper {
     private final Map<String, HttpAuthenticationMechanism> servletAuthenticationMapper = new ConcurrentHashMap<>();
@@ -69,7 +72,13 @@ public class TomEESecurityServletAuthenticationMechanismMapper {
         if (availableBeans.size() == 1) {
             defaultAuthenticationMechanism.setDelegate(availableBeans.iterator().next());
         } else if (availableBeans.size() > 1) {
-            throw new IllegalStateException();
+            throw new IllegalStateException(
+                    "Multiple HttpAuthenticationMechanism found " +
+                    availableBeans.stream()
+                                  .map(b -> substringBefore(b.getClass().getSimpleName(), "$$"))
+                                  .collect(toList()) + " " +
+                    "without a @WebServlet association. " +
+                    "Deploy a single one for the application, or associate it with a @WebServlet.");
         }
     }
 


[tomee] 12/48: TOMEE-2365 - Added default IdentityStore.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit f1315f6c3eea5363272942415145ef34aab6c399
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Mon Dec 24 17:16:06 2018 +0000

    TOMEE-2365 - Added default IdentityStore.
---
 tomee/tomee-security/pom.xml                       | 14 +++++
 .../enterprise/identitystore/IdentityStore.java    | 38 +++++++++++--
 .../identitystore/TomEEDefaultIdentityStore.java   | 64 ++++++++++++++++++++++
 3 files changed, 111 insertions(+), 5 deletions(-)

diff --git a/tomee/tomee-security/pom.xml b/tomee/tomee-security/pom.xml
index 09e19f3..a472bf6 100644
--- a/tomee/tomee-security/pom.xml
+++ b/tomee/tomee-security/pom.xml
@@ -37,8 +37,22 @@
     <dependency>
       <groupId>org.apache.tomee</groupId>
       <artifactId>javaee-api</artifactId>
+      <scope>provided</scope>
     </dependency>
     <dependency>
+      <groupId>org.apache.tomcat</groupId>
+      <artifactId>tomcat-catalina</artifactId>
+      <scope>provided</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.tomee</groupId>
+      <artifactId>tomee-loader</artifactId>
+      <version>${project.version}</version>
+      <scope>provided</scope>
+    </dependency>
+
+    <!-- Test -->
+    <dependency>
       <groupId>${project.groupId}</groupId>
       <artifactId>tomee-embedded</artifactId>
       <version>${project.version}</version>
diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/IdentityStore.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/IdentityStore.java
index badb400..36d2538 100644
--- a/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/IdentityStore.java
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/IdentityStore.java
@@ -17,17 +17,45 @@
 package javax.security.enterprise.identitystore;
 
 import javax.security.enterprise.credential.Credential;
+import java.lang.invoke.MethodHandles;
+import java.util.EnumSet;
 import java.util.Set;
 
+import static java.lang.invoke.MethodType.methodType;
+import static java.util.Collections.emptySet;
+import static javax.security.enterprise.identitystore.CredentialValidationResult.NOT_VALIDATED_RESULT;
+import static javax.security.enterprise.identitystore.IdentityStore.ValidationType.PROVIDE_GROUPS;
+import static javax.security.enterprise.identitystore.IdentityStore.ValidationType.VALIDATE;
+
 public interface IdentityStore {
+    Set<ValidationType> DEFAULT_VALIDATION_TYPES = EnumSet.of(VALIDATE, PROVIDE_GROUPS);
 
-    enum ValidationType { VALIDATE, PROVIDE_GROUPS }
+    default CredentialValidationResult validate(Credential credential) {
+        try {
+            return CredentialValidationResult.class.cast(
+                    MethodHandles.lookup()
+                                 .bind(this, "validate", methodType(CredentialValidationResult.class, credential.getClass()))
+                                 .invoke(credential));
+        } catch (NoSuchMethodException e) {
+            return NOT_VALIDATED_RESULT;
+        } catch (Throwable e) {
+            throw new IllegalStateException(e);
+        }
+    }
 
-    CredentialValidationResult validate(Credential credential);
+    default Set<String> getCallerGroups(CredentialValidationResult validationResult) {
+        return emptySet();
+    }
 
-    Set<String> getCallerGroups(CredentialValidationResult validationResult);
+    default int priority() {
+        return 100;
+    }
 
-    int priority();
+    default Set<ValidationType> validationTypes() {
+        return DEFAULT_VALIDATION_TYPES;
+    }
 
-    Set<ValidationType> validationTypes();
+    enum ValidationType {
+        VALIDATE, PROVIDE_GROUPS
+    }
 }
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/identitystore/TomEEDefaultIdentityStore.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/identitystore/TomEEDefaultIdentityStore.java
new file mode 100644
index 0000000..a687ae1
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/identitystore/TomEEDefaultIdentityStore.java
@@ -0,0 +1,64 @@
+/*
+ * 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.tomee.security.identitystore;
+
+import org.apache.catalina.User;
+import org.apache.catalina.UserDatabase;
+import org.apache.catalina.core.StandardServer;
+import org.apache.catalina.deploy.NamingResourcesImpl;
+import org.apache.tomcat.util.descriptor.web.ContextResource;
+import org.apache.tomee.loader.TomcatHelper;
+
+import javax.annotation.PostConstruct;
+import javax.enterprise.context.ApplicationScoped;
+import javax.security.enterprise.credential.UsernamePasswordCredential;
+import javax.security.enterprise.identitystore.CredentialValidationResult;
+import javax.security.enterprise.identitystore.IdentityStore;
+import java.util.HashSet;
+import java.util.Optional;
+import java.util.Set;
+
+@ApplicationScoped
+public class TomEEDefaultIdentityStore implements IdentityStore {
+    private UserDatabase userDatabase;
+
+    @PostConstruct
+    private void init() throws Exception {
+        final StandardServer server = TomcatHelper.getServer();
+        final NamingResourcesImpl resources = server.getGlobalNamingResources();
+        final ContextResource userDataBaseResource = resources.findResource("UserDatabase");
+        userDatabase = (UserDatabase) server.getGlobalNamingContext().lookup(userDataBaseResource.getName());
+    }
+
+    public CredentialValidationResult validate(final UsernamePasswordCredential credential) {
+        return Optional.ofNullable(userDatabase.findUser(credential.getCaller()))
+                       .filter(user -> user.getPassword().equals(credential.getPasswordAsString()))
+                       .map(user -> new CredentialValidationResult(user.getUsername(), getUserRoles(user)))
+                       .orElse(CredentialValidationResult.INVALID_RESULT);
+    }
+
+    @Override
+    public Set<String> getCallerGroups(final CredentialValidationResult validationResult) {
+        return validationResult.getCallerGroups();
+    }
+
+    private Set<String> getUserRoles(final User user) {
+        final Set<String> roles = new HashSet<>();
+        user.getRoles().forEachRemaining(role -> roles.add(role.getRolename()));
+        return roles;
+    }
+}


[tomee] 35/48: TOMEE-2365 - Actual implementation of the form authentication validation.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit 6121de4d9231b119625f9148455603199139fa46
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Fri Dec 28 13:11:22 2018 +0000

    TOMEE-2365 - Actual implementation of the form authentication validation.
---
 .../security/cdi/FormAuthenticationMechanism.java  | 22 +++++++++++++++++++++-
 1 file changed, 21 insertions(+), 1 deletion(-)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/FormAuthenticationMechanism.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/FormAuthenticationMechanism.java
index 8846a7a..f60e7ea 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/FormAuthenticationMechanism.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/FormAuthenticationMechanism.java
@@ -25,8 +25,11 @@ import javax.security.enterprise.AuthenticationStatus;
 import javax.security.enterprise.authentication.mechanism.http.HttpAuthenticationMechanism;
 import javax.security.enterprise.authentication.mechanism.http.HttpMessageContext;
 import javax.security.enterprise.authentication.mechanism.http.LoginToContinue;
+import javax.security.enterprise.credential.UsernamePasswordCredential;
+import javax.security.enterprise.identitystore.IdentityStoreHandler;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.HttpMethod;
 import java.util.function.Supplier;
 
 @ApplicationScoped
@@ -34,12 +37,23 @@ import java.util.function.Supplier;
 public class FormAuthenticationMechanism implements HttpAuthenticationMechanism, LoginToContinueMechanism {
     @Inject
     private Supplier<LoginToContinue> loginToContinue;
+    @Inject
+    private IdentityStoreHandler identityStoreHandler;
 
     @Override
     public AuthenticationStatus validateRequest(final HttpServletRequest request, final HttpServletResponse response,
                                                 final HttpMessageContext httpMessageContext)
             throws AuthenticationException {
-        throw new UnsupportedOperationException();
+
+        final String username = request.getParameter("j_username");
+        final String password = request.getParameter("j_password");
+
+        if (validateForm(httpMessageContext.getRequest(), username, password)) {
+            return httpMessageContext.notifyContainerAboutLogin(
+                    identityStoreHandler.validate(new UsernamePasswordCredential(username, password)));
+        }
+
+        return httpMessageContext.doNothing();
     }
 
     @Override
@@ -58,4 +72,10 @@ public class FormAuthenticationMechanism implements HttpAuthenticationMechanism,
     public LoginToContinue getLoginToContinue() {
         return loginToContinue.get();
     }
+
+    private boolean validateForm(final HttpServletRequest request, final String username, final String password) {
+        return request.getMethod().equals(HttpMethod.POST) &&
+               username != null && !username.isEmpty() &&
+               password != null && !password.isEmpty();
+    }
 }


[tomee] 40/48: TOMEE-2365 - Implemented AutoApplySessionInterceptor.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit 429493011b829ffe33def7db0082bc3081eae7b7
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Mon Jan 7 17:04:42 2019 +0000

    TOMEE-2365 - Implemented AutoApplySessionInterceptor.
---
 .../security/cdi/AutoApplySessionInterceptor.java  | 76 ++++++++++++++++++++++
 .../tomee/security/cdi/TomEESecurityExtension.java |  1 +
 2 files changed, 77 insertions(+)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/AutoApplySessionInterceptor.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/AutoApplySessionInterceptor.java
new file mode 100644
index 0000000..5ed0aaa
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/AutoApplySessionInterceptor.java
@@ -0,0 +1,76 @@
+/*
+ * 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.tomee.security.cdi;
+
+import javax.annotation.Priority;
+import javax.interceptor.AroundInvoke;
+import javax.interceptor.Interceptor;
+import javax.interceptor.InvocationContext;
+import javax.security.auth.callback.Callback;
+import javax.security.auth.message.callback.CallerPrincipalCallback;
+import javax.security.enterprise.AuthenticationStatus;
+import javax.security.enterprise.authentication.mechanism.http.AutoApplySession;
+import javax.security.enterprise.authentication.mechanism.http.HttpMessageContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.security.Principal;
+import java.util.Arrays;
+
+import static javax.interceptor.Interceptor.Priority.PLATFORM_BEFORE;
+
+@AutoApplySession
+@Interceptor
+@Priority(PLATFORM_BEFORE + 200)
+public class AutoApplySessionInterceptor {
+    @AroundInvoke
+    public Object intercept(final InvocationContext invocationContext) throws Exception {
+        if (invocationContext.getMethod().getName().equals("validateRequest") &&
+            Arrays.equals(invocationContext.getMethod().getParameterTypes(), new Class<?>[]{
+                    HttpServletRequest.class,
+                    HttpServletResponse.class,
+                    HttpMessageContext.class
+            })) {
+            return validateRequest(invocationContext);
+        }
+
+        return invocationContext.proceed();
+    }
+
+    private AuthenticationStatus validateRequest(final InvocationContext invocationContext)
+            throws Exception {
+
+        final HttpMessageContext httpMessageContext = (HttpMessageContext) invocationContext.getParameters()[2];
+
+        final Principal principal = httpMessageContext.getRequest().getUserPrincipal();
+        if (principal == null) {
+            final Object authenticationStatus = invocationContext.proceed();
+
+            if (AuthenticationStatus.SUCCESS.equals(authenticationStatus)) {
+                httpMessageContext.getMessageInfo().getMap().put("javax.servlet.http.registerSession", "true");
+            }
+
+            return (AuthenticationStatus) authenticationStatus;
+        } else {
+            final CallerPrincipalCallback callerPrincipalCallback =
+                    new CallerPrincipalCallback(httpMessageContext.getClientSubject(), principal);
+
+            httpMessageContext.getHandler().handle(new Callback[] {callerPrincipalCallback});
+
+            return AuthenticationStatus.SUCCESS;
+        }
+    }
+}
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityExtension.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityExtension.java
index 2fb9ef5..9343c3e 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityExtension.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityExtension.java
@@ -53,6 +53,7 @@ public class TomEESecurityExtension implements Extension {
         beforeBeanDiscovery.addAnnotatedType(beanManager.createAnnotatedType(TomEEDefaultIdentityStore.class));
         beforeBeanDiscovery.addAnnotatedType(beanManager.createAnnotatedType(TomEEIdentityStoreHandler.class));
 
+        beforeBeanDiscovery.addAnnotatedType(beanManager.createAnnotatedType(AutoApplySessionInterceptor.class));
         beforeBeanDiscovery.addAnnotatedType(beanManager.createAnnotatedType(LoginToContinueInterceptor.class));
     }
 


[tomee] 47/48: TOMEE-2365 - Fixed layer and appContextId with values used by Tomcat.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit 62431cf090c86d4cfa8cbd69164200abcd0f5a90
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Tue Jan 8 19:35:01 2019 +0000

    TOMEE-2365 - Fixed layer and appContextId with values used by Tomcat.
---
 .../security/servlet/TomEESecurityServletContainerInitializer.java    | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/servlet/TomEESecurityServletContainerInitializer.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/servlet/TomEESecurityServletContainerInitializer.java
index b3e1424..2204973 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/servlet/TomEESecurityServletContainerInitializer.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/servlet/TomEESecurityServletContainerInitializer.java
@@ -35,8 +35,8 @@ public class TomEESecurityServletContainerInitializer implements ServletContaine
         if (securityExtension.hasAuthenticationMechanisms()) {
             AuthConfigFactory.getFactory().registerConfigProvider(
                     new TomEESecurityAuthConfigProvider(),
-                    "http",
-                    ctx.getContextPath().length() == 0 ? "root" : ctx.getContextPath(),
+                    "HttpServlet",                                              // from AuthenticatorBase.java:1245
+                    ctx.getVirtualServerName() + " " + ctx.getContextPath(),    // from AuthenticatorBase.java:1178
                     "TomEE Security JSR-375");
         }
     }


[tomee] 18/48: TOMEE-2365 - Properly override validate method on default Identity Store.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit 627224f89078b0e1adad09864ca3b471f534e8e0
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Wed Dec 26 16:15:36 2018 +0000

    TOMEE-2365 - Properly override validate method on default Identity Store.
---
 .../identitystore/TomEEDefaultIdentityStore.java        | 17 ++++++++++++-----
 1 file changed, 12 insertions(+), 5 deletions(-)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/identitystore/TomEEDefaultIdentityStore.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/identitystore/TomEEDefaultIdentityStore.java
index a687ae1..48caa07 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/identitystore/TomEEDefaultIdentityStore.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/identitystore/TomEEDefaultIdentityStore.java
@@ -25,6 +25,7 @@ import org.apache.tomee.loader.TomcatHelper;
 
 import javax.annotation.PostConstruct;
 import javax.enterprise.context.ApplicationScoped;
+import javax.security.enterprise.credential.Credential;
 import javax.security.enterprise.credential.UsernamePasswordCredential;
 import javax.security.enterprise.identitystore.CredentialValidationResult;
 import javax.security.enterprise.identitystore.IdentityStore;
@@ -44,11 +45,17 @@ public class TomEEDefaultIdentityStore implements IdentityStore {
         userDatabase = (UserDatabase) server.getGlobalNamingContext().lookup(userDataBaseResource.getName());
     }
 
-    public CredentialValidationResult validate(final UsernamePasswordCredential credential) {
-        return Optional.ofNullable(userDatabase.findUser(credential.getCaller()))
-                       .filter(user -> user.getPassword().equals(credential.getPasswordAsString()))
-                       .map(user -> new CredentialValidationResult(user.getUsername(), getUserRoles(user)))
-                       .orElse(CredentialValidationResult.INVALID_RESULT);
+    @Override
+    public CredentialValidationResult validate(final Credential credential) {
+        if (credential instanceof UsernamePasswordCredential) {
+            final UsernamePasswordCredential usernamePasswordCredential = (UsernamePasswordCredential) credential;
+            return Optional.ofNullable(userDatabase.findUser(usernamePasswordCredential.getCaller()))
+                           .filter(user -> user.getPassword().equals(usernamePasswordCredential.getPasswordAsString()))
+                           .map(user -> new CredentialValidationResult(user.getUsername(), getUserRoles(user)))
+                           .orElse(CredentialValidationResult.INVALID_RESULT);
+        }
+
+        return CredentialValidationResult.NOT_VALIDATED_RESULT;
     }
 
     @Override


[tomee] 19/48: TOMEE-2365 - Initial implementation of HttpMessageContext. Not complete yet, just basic stuff.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit 7366bbd3d7dc174ac86703cf4246ec5ebc5b3c70
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Wed Dec 26 16:17:28 2018 +0000

    TOMEE-2365 - Initial implementation of HttpMessageContext. Not complete yet, just basic stuff.
---
 .../security/http/TomEEHttpMessageContext.java     | 190 +++++++++++++++++++++
 1 file changed, 190 insertions(+)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/TomEEHttpMessageContext.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/TomEEHttpMessageContext.java
new file mode 100644
index 0000000..dfb7627
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/TomEEHttpMessageContext.java
@@ -0,0 +1,190 @@
+/*
+ * 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.tomee.security.http;
+
+import org.apache.catalina.authenticator.jaspic.MessageInfoImpl;
+
+import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.message.MessageInfo;
+import javax.security.enterprise.AuthenticationStatus;
+import javax.security.enterprise.CallerPrincipal;
+import javax.security.enterprise.authentication.mechanism.http.AuthenticationParameters;
+import javax.security.enterprise.authentication.mechanism.http.HttpMessageContext;
+import javax.security.enterprise.identitystore.CredentialValidationResult;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.security.Principal;
+import java.util.Set;
+
+import static javax.security.enterprise.AuthenticationStatus.SEND_FAILURE;
+import static javax.security.enterprise.AuthenticationStatus.SUCCESS;
+import static javax.security.enterprise.identitystore.CredentialValidationResult.Status.VALID;
+import static javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED;
+
+public class TomEEHttpMessageContext implements HttpMessageContext {
+    private final MessageInfo messageInfo;
+    private final Subject clientSubject;
+    private final Subject serviceSubject;
+
+    private TomEEHttpMessageContext(final MessageInfo messageInfo,
+                                    final Subject clientSubject,
+                                    final Subject serviceSubject) {
+        this.messageInfo = messageInfo;
+        this.clientSubject = clientSubject;
+        this.serviceSubject = serviceSubject;
+    }
+
+    public static TomEEHttpMessageContext httpMessageContext(final MessageInfo messageInfo,
+                                                             final Subject clientSubject,
+                                                             final Subject serviceSubject) {
+        return new TomEEHttpMessageContext(messageInfo, clientSubject, serviceSubject);
+    }
+
+    @Override
+    public boolean isProtected() {
+        return Boolean.valueOf((String) messageInfo.getMap().getOrDefault(MessageInfoImpl.IS_MANDATORY, "false"));
+    }
+
+    @Override
+    public boolean isAuthenticationRequest() {
+        return false;
+    }
+
+    @Override
+    public boolean isRegisterSession() {
+        return false;
+    }
+
+    @Override
+    public void setRegisterSession(final String callerName, final Set<String> groups) {
+
+    }
+
+    @Override
+    public void cleanClientSubject() {
+
+    }
+
+    @Override
+    public AuthenticationParameters getAuthParameters() {
+        return null;
+    }
+
+    @Override
+    public CallbackHandler getHandler() {
+        return null;
+    }
+
+    @Override
+    public MessageInfo getMessageInfo() {
+        return null;
+    }
+
+    @Override
+    public Subject getClientSubject() {
+        return null;
+    }
+
+    @Override
+    public HttpServletRequest getRequest() {
+        return (HttpServletRequest) messageInfo.getRequestMessage();
+    }
+
+    @Override
+    public void setRequest(final HttpServletRequest request) {
+        messageInfo.setRequestMessage(request);
+    }
+
+    @Override
+    public HttpMessageContext withRequest(final HttpServletRequest request) {
+        setRequest(request);
+        return this;
+    }
+
+    @Override
+    public HttpServletResponse getResponse() {
+        return (HttpServletResponse) messageInfo.getResponseMessage();
+    }
+
+    @Override
+    public void setResponse(final HttpServletResponse response) {
+        messageInfo.setResponseMessage(response);
+    }
+
+    @Override
+    public AuthenticationStatus redirect(final String location) {
+        return null;
+    }
+
+    @Override
+    public AuthenticationStatus forward(final String path) {
+        return null;
+    }
+
+    @Override
+    public AuthenticationStatus responseUnauthorized() {
+        try {
+            getResponse().sendError(SC_UNAUTHORIZED);
+        } catch (final IOException e) {
+            throw new IllegalStateException(e);
+        }
+        return SEND_FAILURE;
+    }
+
+    @Override
+    public AuthenticationStatus responseNotFound() {
+        return null;
+    }
+
+    @Override
+    public AuthenticationStatus notifyContainerAboutLogin(final String callername, final Set<String> groups) {
+        return notifyContainerAboutLogin(new CallerPrincipal(callername), groups);
+    }
+
+    @Override
+    public AuthenticationStatus notifyContainerAboutLogin(final Principal principal, final Set<String> groups) {
+        // Needs more stuff in here.
+
+        return SUCCESS;
+    }
+
+    @Override
+    public AuthenticationStatus notifyContainerAboutLogin(final CredentialValidationResult result) {
+        if (result.getStatus().equals(VALID)) {
+            return notifyContainerAboutLogin(result.getCallerPrincipal(), result.getCallerGroups());
+        }
+
+        return SEND_FAILURE;
+    }
+
+    @Override
+    public AuthenticationStatus doNothing() {
+        return null;
+    }
+
+    @Override
+    public Principal getCallerPrincipal() {
+        return null;
+    }
+
+    @Override
+    public Set<String> getGroups() {
+        return null;
+    }
+}


[tomee] 25/48: TOMEE-2365 - Refactored tests to be more scalable.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit b485d4b749965fdc7bf3d017a9a4a704742de910
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Wed Dec 26 19:16:27 2018 +0000

    TOMEE-2365 - Refactored tests to be more scalable.
---
 ...letTest.java => AbstractTomEESecurityTest.java} | 45 ++++++----------------
 .../security/servlet/BasicAuthServletTest.java     | 41 ++++++++------------
 .../tomee/security/servlet/SimpleServletTest.java  | 29 ++++----------
 3 files changed, 34 insertions(+), 81 deletions(-)

diff --git a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/AbstractTomEESecurityTest.java
similarity index 52%
copy from tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java
copy to tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/AbstractTomEESecurityTest.java
index 5d11cbc..7e80ce2 100644
--- a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java
+++ b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/AbstractTomEESecurityTest.java
@@ -20,48 +20,27 @@ import org.apache.openejb.loader.JarLocation;
 import org.apache.openejb.util.NetworkUtil;
 import org.apache.tomee.embedded.Configuration;
 import org.apache.tomee.embedded.Container;
-import org.junit.Test;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
 
-import javax.servlet.ServletException;
-import javax.servlet.annotation.WebServlet;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.ws.rs.client.Client;
-import javax.ws.rs.client.ClientBuilder;
-import javax.ws.rs.core.Response;
-import java.io.IOException;
+public abstract class AbstractTomEESecurityTest {
+    protected static Container container;
 
-import static org.junit.Assert.assertEquals;
-
-public class SimpleServletTest {
-    @Test
-    public void testWebApp() throws Exception {
-        try (Container container = new Container(
+    @BeforeClass
+    public static void setUp() throws Exception {
+        container = new Container(
                 new Configuration()
                         .conf("conf")
                         .http(NetworkUtil.getNextAvailablePort())
                         .property("openejb.container.additional.exclude", "org.apache.tomee.security.")
                         .property("openejb.additional.include", "tomee-"))
                 .deployPathsAsWebapp(
-                        JarLocation.jarLocation(SimpleServletTest.class),
-                        JarLocation.jarLocation(TomEESecurityServletContainerInitializer.class))) {
-
-            final Client client = ClientBuilder.newBuilder().build();
-            final Response response =
-                    client.target("http://localhost:" + container.getConfiguration().getHttpPort() + "/servlet")
-                          .request()
-                          .get();
-            assertEquals(200, response.getStatus());
-        }
+                        JarLocation.jarLocation(AbstractTomEESecurityTest.class),
+                        JarLocation.jarLocation(TomEESecurityServletContainerInitializer.class));
     }
 
-    @WebServlet(urlPatterns = "/servlet")
-    public static class TestServlet extends HttpServlet {
-        @Override
-        protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
-                throws ServletException, IOException {
-            resp.getWriter().write("ok!");
-        }
+    @AfterClass
+    public static void tearDown() throws Exception {
+        container.close();
     }
 }
diff --git a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/BasicAuthServletTest.java b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/BasicAuthServletTest.java
index b25f169..e0fd2c6 100644
--- a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/BasicAuthServletTest.java
+++ b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/BasicAuthServletTest.java
@@ -16,10 +16,6 @@
  */
 package org.apache.tomee.security.servlet;
 
-import org.apache.openejb.loader.JarLocation;
-import org.apache.openejb.util.NetworkUtil;
-import org.apache.tomee.embedded.Configuration;
-import org.apache.tomee.embedded.Container;
 import org.apache.tomee.security.client.BasicAuthFilter;
 import org.junit.Test;
 
@@ -36,31 +32,24 @@ import java.io.IOException;
 
 import static org.junit.Assert.assertEquals;
 
-public class BasicAuthServletTest {
+public class BasicAuthServletTest extends AbstractTomEESecurityTest {
     @Test
-    public void testWebApp() throws Exception {
-        try (Container container = new Container(
-                new Configuration()
-                        .conf("conf")
-                        .http(NetworkUtil.getNextAvailablePort())
-                        .property("openejb.container.additional.exclude", "org.apache.tomee.security.")
-                        .property("openejb.additional.include", "tomee-"))
-                .deployPathsAsWebapp(
-                        JarLocation.jarLocation(SimpleServletTest.class),
-                        JarLocation.jarLocation(TomEESecurityServletContainerInitializer.class))) {
-
-            final String servlet = "http://localhost:" + container.getConfiguration().getHttpPort() + "/basic";
+    public void authenticate() throws Exception {
+        final String servlet = "http://localhost:" + container.getConfiguration().getHttpPort() + "/basic";
+        assertEquals(200, ClientBuilder.newBuilder().register(new BasicAuthFilter()).build()
+                                       .target(servlet)
+                                       .request()
+                                       .get().getStatus());
+    }
 
-            assertEquals(401, ClientBuilder.newBuilder().build()
-                                           .target(servlet)
-                                           .request()
-                                           .get().getStatus());
+    @Test
+    public void missingAuthorizationHeader() throws Exception {
+        final String servlet = "http://localhost:" + container.getConfiguration().getHttpPort() + "/basic";
 
-            assertEquals(200, ClientBuilder.newBuilder().register(new BasicAuthFilter()).build()
-                                   .target(servlet)
-                                   .request()
-                                   .get().getStatus());
-        }
+        assertEquals(401, ClientBuilder.newBuilder().build()
+                                       .target(servlet)
+                                       .request()
+                                       .get().getStatus());
     }
 
     @WebServlet(urlPatterns = "/basic")
diff --git a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java
index 5d11cbc..e45e2ed 100644
--- a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java
+++ b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java
@@ -16,10 +16,6 @@
  */
 package org.apache.tomee.security.servlet;
 
-import org.apache.openejb.loader.JarLocation;
-import org.apache.openejb.util.NetworkUtil;
-import org.apache.tomee.embedded.Configuration;
-import org.apache.tomee.embedded.Container;
 import org.junit.Test;
 
 import javax.servlet.ServletException;
@@ -34,26 +30,15 @@ import java.io.IOException;
 
 import static org.junit.Assert.assertEquals;
 
-public class SimpleServletTest {
+public class SimpleServletTest extends AbstractTomEESecurityTest {
     @Test
     public void testWebApp() throws Exception {
-        try (Container container = new Container(
-                new Configuration()
-                        .conf("conf")
-                        .http(NetworkUtil.getNextAvailablePort())
-                        .property("openejb.container.additional.exclude", "org.apache.tomee.security.")
-                        .property("openejb.additional.include", "tomee-"))
-                .deployPathsAsWebapp(
-                        JarLocation.jarLocation(SimpleServletTest.class),
-                        JarLocation.jarLocation(TomEESecurityServletContainerInitializer.class))) {
-
-            final Client client = ClientBuilder.newBuilder().build();
-            final Response response =
-                    client.target("http://localhost:" + container.getConfiguration().getHttpPort() + "/servlet")
-                          .request()
-                          .get();
-            assertEquals(200, response.getStatus());
-        }
+        final Client client = ClientBuilder.newBuilder().build();
+        final Response response =
+                client.target("http://localhost:" + container.getConfiguration().getHttpPort() + "/servlet")
+                      .request()
+                      .get();
+        assertEquals(200, response.getStatus());
     }
 
     @WebServlet(urlPatterns = "/servlet")


[tomee] 39/48: TOMEE-2365 - Added AutoApplySession annotation to the API.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit b4c85be1da31d44c8646b7ae684b5c3ce34acd88
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Mon Jan 7 15:57:06 2019 +0000

    TOMEE-2365 - Added AutoApplySession annotation to the API.
---
 .../mechanism/http/AutoApplySession.java           | 32 ++++++++++++++++++++++
 1 file changed, 32 insertions(+)

diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/AutoApplySession.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/AutoApplySession.java
new file mode 100644
index 0000000..6af744b
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/AutoApplySession.java
@@ -0,0 +1,32 @@
+/*
+ * 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 javax.security.enterprise.authentication.mechanism.http;
+
+import javax.interceptor.InterceptorBinding;
+import java.lang.annotation.Inherited;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+@Inherited
+@InterceptorBinding
+@Retention(RUNTIME)
+@Target(TYPE)
+public @interface AutoApplySession {
+}


[tomee] 46/48: TOMEE-2365 - Default appContext to root when context path is empty.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit 8242f23e3e971e14f31ed0d561b52b7e343ce731
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Tue Jan 8 18:54:45 2019 +0000

    TOMEE-2365 - Default appContext to root when context path is empty.
---
 .../servlet/TomEESecurityServletContainerInitializer.java        | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/servlet/TomEESecurityServletContainerInitializer.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/servlet/TomEESecurityServletContainerInitializer.java
index fcf8452..b3e1424 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/servlet/TomEESecurityServletContainerInitializer.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/servlet/TomEESecurityServletContainerInitializer.java
@@ -33,10 +33,11 @@ public class TomEESecurityServletContainerInitializer implements ServletContaine
                 CDI.current().getBeanManager().getExtension(TomEESecurityExtension.class);
 
         if (securityExtension.hasAuthenticationMechanisms()) {
-            AuthConfigFactory.getFactory()
-                             .registerConfigProvider(new TomEESecurityAuthConfigProvider(),
-                                                     "http", ctx.getVirtualServerName() + " " + ctx.getContextPath(),
-                                                     "TomEE Security JSR-375");
+            AuthConfigFactory.getFactory().registerConfigProvider(
+                    new TomEESecurityAuthConfigProvider(),
+                    "http",
+                    ctx.getContextPath().length() == 0 ? "root" : ctx.getContextPath(),
+                    "TomEE Security JSR-375");
         }
     }
 }


[tomee] 11/48: TOMEE-2365 - Only register JASPIC provider if AuthenticationMechanism exist in the CDI context.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit 36543b8991ad219db3cb575138e80fff58747b69
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Tue Dec 18 23:32:03 2018 +0000

    TOMEE-2365 - Only register JASPIC provider if AuthenticationMechanism exist in the CDI context.
---
 .../servlet/TomEESecurityServletContainerInitializer.java      | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/servlet/TomEESecurityServletContainerInitializer.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/servlet/TomEESecurityServletContainerInitializer.java
index fd49140..7eba191 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/servlet/TomEESecurityServletContainerInitializer.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/servlet/TomEESecurityServletContainerInitializer.java
@@ -18,7 +18,9 @@ package org.apache.tomee.security.servlet;
 
 import org.apache.tomee.security.provider.TomEESecurityAuthConfigProvider;
 
+import javax.enterprise.inject.spi.CDI;
 import javax.security.auth.message.config.AuthConfigFactory;
+import javax.security.enterprise.authentication.mechanism.http.HttpAuthenticationMechanism;
 import javax.servlet.ServletContainerInitializer;
 import javax.servlet.ServletContext;
 import javax.servlet.ServletException;
@@ -27,8 +29,10 @@ import java.util.Set;
 public class TomEESecurityServletContainerInitializer implements ServletContainerInitializer {
     @Override
     public void onStartup(final Set<Class<?>> c, final ServletContext ctx) throws ServletException {
-        AuthConfigFactory.getFactory()
-                         .registerConfigProvider(new TomEESecurityAuthConfigProvider(), null, null,
-                                                 "TomEE Security JSR-375");
+        if (CDI.current().select(HttpAuthenticationMechanism.class).isResolvable()) {
+            AuthConfigFactory.getFactory()
+                             .registerConfigProvider(new TomEESecurityAuthConfigProvider(), null, null,
+                                                     "TomEE Security JSR-375");
+        }
     }
 }


[tomee] 27/48: TOMEE-2365 - Initial implementation and wiring of FormAuthenticationMechanism.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit 200a84e80586d85319de19a7ecfb08fc69243c17
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Thu Dec 27 12:31:49 2018 +0000

    TOMEE-2365 - Initial implementation and wiring of FormAuthenticationMechanism.
---
 .../security/cdi/FormAuthenticationMechanism.java  | 48 +++++++++++++
 .../tomee/security/cdi/TomEESecurityExtension.java | 81 +++++++++++++++-------
 ...curityServletAuthenticationMechanismMapper.java |  7 ++
 .../security/servlet/FormAuthServletTest.java      | 81 ++++++++++++++++++++++
 4 files changed, 192 insertions(+), 25 deletions(-)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/FormAuthenticationMechanism.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/FormAuthenticationMechanism.java
new file mode 100644
index 0000000..b7a29e8
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/FormAuthenticationMechanism.java
@@ -0,0 +1,48 @@
+/*
+ * 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.tomee.security.cdi;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.security.enterprise.AuthenticationException;
+import javax.security.enterprise.AuthenticationStatus;
+import javax.security.enterprise.authentication.mechanism.http.HttpAuthenticationMechanism;
+import javax.security.enterprise.authentication.mechanism.http.HttpMessageContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+@ApplicationScoped
+public class FormAuthenticationMechanism implements HttpAuthenticationMechanism {
+    @Override
+    public AuthenticationStatus validateRequest(final HttpServletRequest request, final HttpServletResponse response,
+                                                final HttpMessageContext httpMessageContext)
+            throws AuthenticationException {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public AuthenticationStatus secureResponse(final HttpServletRequest request, final HttpServletResponse response,
+                                               final HttpMessageContext httpMessageContext)
+            throws AuthenticationException {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public void cleanSubject(final HttpServletRequest request, final HttpServletResponse response,
+                             final HttpMessageContext httpMessageContext) {
+        throw new UnsupportedOperationException();
+    }
+}
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityExtension.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityExtension.java
index 712587e..91036c9 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityExtension.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityExtension.java
@@ -31,51 +31,82 @@ import javax.enterprise.inject.spi.BeanManager;
 import javax.enterprise.inject.spi.BeforeBeanDiscovery;
 import javax.enterprise.inject.spi.Extension;
 import javax.enterprise.inject.spi.ProcessAnnotatedType;
+import javax.enterprise.inject.spi.WithAnnotations;
 import javax.security.enterprise.authentication.mechanism.http.BasicAuthenticationMechanismDefinition;
+import javax.security.enterprise.authentication.mechanism.http.FormAuthenticationMechanismDefinition;
 import javax.security.enterprise.authentication.mechanism.http.HttpAuthenticationMechanism;
 import java.util.HashSet;
 import java.util.Set;
 
 public class TomEESecurityExtension implements Extension {
     private final Set<AnnotatedType> basicAuthentication = new HashSet<>();
+    private final Set<AnnotatedType> formAuthentication = new HashSet<>();
 
-    void processAuthenticationMechanismDefinitions(@Observes final ProcessAnnotatedType<?> processAnnotatedType) {
+    void observeBeforeBeanDiscovery(@Observes final BeforeBeanDiscovery beforeBeanDiscovery,
+                                    final BeanManager beanManager) {
+        beforeBeanDiscovery.addAnnotatedType(beanManager.createAnnotatedType(DefaultAuthenticationMechanism.class));
+        beforeBeanDiscovery.addAnnotatedType(
+                beanManager.createAnnotatedType(TomEESecurityServletAuthenticationMechanismMapper.class));
+        beforeBeanDiscovery.addAnnotatedType(beanManager.createAnnotatedType(TomEEDefaultIdentityStore.class));
+        beforeBeanDiscovery.addAnnotatedType(beanManager.createAnnotatedType(TomEEIdentityStoreHandler.class));
+    }
+
+    void processAuthenticationMechanismDefinitions(@Observes
+                                                   @WithAnnotations({
+                                                           BasicAuthenticationMechanismDefinition.class,
+                                                           FormAuthenticationMechanismDefinition.class
+                                                   }) final ProcessAnnotatedType<?> processAnnotatedType) {
         final AnnotatedType<?> annotatedType = processAnnotatedType.getAnnotatedType();
+
         if (annotatedType.isAnnotationPresent(BasicAuthenticationMechanismDefinition.class)) {
             basicAuthentication.add(annotatedType);
         }
-    }
 
-    void observeBeforeBeanDiscovery(@Observes final BeforeBeanDiscovery beforeBeanDiscovery,
-                                    final BeanManager beanManager) {
-        if (basicAuthentication.isEmpty()) {
-            beforeBeanDiscovery.addAnnotatedType(beanManager.createAnnotatedType(DefaultAuthenticationMechanism.class));
-            beforeBeanDiscovery.addAnnotatedType(
-                    beanManager.createAnnotatedType(TomEESecurityServletAuthenticationMechanismMapper.class));
-            beforeBeanDiscovery.addAnnotatedType(beanManager.createAnnotatedType(TomEEDefaultIdentityStore.class));
-            beforeBeanDiscovery.addAnnotatedType(beanManager.createAnnotatedType(TomEEIdentityStoreHandler.class));
+        if (annotatedType.isAnnotationPresent(FormAuthenticationMechanismDefinition.class)) {
+            formAuthentication.add(annotatedType);
         }
     }
 
     void registerAuthenticationMechanism(@Observes final AfterBeanDiscovery afterBeanDiscovery,
                                          final BeanManager beanManager) {
         if (!basicAuthentication.isEmpty()) {
-            afterBeanDiscovery.addBean()
-               .id(BasicAuthenticationMechanism.class.getName())
-               .beanClass(BasicAuthenticationMechanism.class)
-               .types(Object.class, HttpAuthenticationMechanism.class, BasicAuthenticationMechanism.class)
-               .qualifiers(Default.Literal.INSTANCE, Any.Literal.INSTANCE)
-               .scope(ApplicationScoped.class)
-               .createWith((CreationalContext<BasicAuthenticationMechanism> creationalContext) -> {
-                   AnnotatedType<BasicAuthenticationMechanism> annotatedType =
-                           beanManager.createAnnotatedType(BasicAuthenticationMechanism.class);
-                   BeanAttributes<BasicAuthenticationMechanism> beanAttributes =
-                           beanManager.createBeanAttributes(annotatedType);
-                   return beanManager.createBean(beanAttributes, BasicAuthenticationMechanism.class,
-                                                 beanManager.getInjectionTargetFactory(annotatedType))
-                                     .create(creationalContext);
-               });
+            afterBeanDiscovery
+                    .addBean()
+                    .id(BasicAuthenticationMechanism.class.getName())
+                    .beanClass(BasicAuthenticationMechanism.class)
+                    .types(Object.class, HttpAuthenticationMechanism.class, BasicAuthenticationMechanism.class)
+                    .qualifiers(Default.Literal.INSTANCE, Any.Literal.INSTANCE)
+                    .scope(ApplicationScoped.class)
+                    .createWith((CreationalContext<BasicAuthenticationMechanism> creationalContext) -> {
+                        AnnotatedType<BasicAuthenticationMechanism> annotatedType =
+                                beanManager.createAnnotatedType(BasicAuthenticationMechanism.class);
+                        BeanAttributes<BasicAuthenticationMechanism> beanAttributes =
+                                beanManager.createBeanAttributes(annotatedType);
+                        return beanManager.createBean(beanAttributes, BasicAuthenticationMechanism.class,
+                                                      beanManager.getInjectionTargetFactory(annotatedType))
+                                          .create(creationalContext);
+                    });
         }
+
+        if (!formAuthentication.isEmpty()) {
+            afterBeanDiscovery
+                    .addBean()
+                    .id(FormAuthenticationMechanism.class.getName())
+                    .beanClass(FormAuthenticationMechanism.class)
+                    .types(Object.class, HttpAuthenticationMechanism.class, FormAuthenticationMechanism.class)
+                    .qualifiers(Default.Literal.INSTANCE, Any.Literal.INSTANCE)
+                    .scope(ApplicationScoped.class)
+                    .createWith((CreationalContext<FormAuthenticationMechanism> creationalContext) -> {
+                        AnnotatedType<FormAuthenticationMechanism> annotatedType =
+                                beanManager.createAnnotatedType(FormAuthenticationMechanism.class);
+                        BeanAttributes<FormAuthenticationMechanism> beanAttributes =
+                                beanManager.createBeanAttributes(annotatedType);
+                        return beanManager.createBean(beanAttributes, FormAuthenticationMechanism.class,
+                                                      beanManager.getInjectionTargetFactory(annotatedType))
+                                          .create(creationalContext);
+                    });
+        }
+
     }
 
     public boolean hasAuthenticationMechanisms() {
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityServletAuthenticationMechanismMapper.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityServletAuthenticationMechanismMapper.java
index 836fff4..fff782e 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityServletAuthenticationMechanismMapper.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityServletAuthenticationMechanismMapper.java
@@ -22,6 +22,7 @@ import javax.enterprise.event.Observes;
 import javax.enterprise.inject.spi.CDI;
 import javax.inject.Inject;
 import javax.security.enterprise.authentication.mechanism.http.BasicAuthenticationMechanismDefinition;
+import javax.security.enterprise.authentication.mechanism.http.FormAuthenticationMechanismDefinition;
 import javax.security.enterprise.authentication.mechanism.http.HttpAuthenticationMechanism;
 import javax.servlet.ServletContext;
 import javax.servlet.ServletRegistration;
@@ -44,6 +45,12 @@ public class TomEESecurityServletAuthenticationMechanismMapper {
                     servletAuthenticationMapper.put(servletName,
                                                     CDI.current().select(BasicAuthenticationMechanism.class).get());
                 }
+
+                if (servletClass.isAnnotationPresent(FormAuthenticationMechanismDefinition.class)) {
+                    servletAuthenticationMapper.put(servletName,
+                                                    CDI.current().select(FormAuthenticationMechanism.class).get());
+                }
+
             } catch (final ClassNotFoundException e) {
                 // Ignore
             }
diff --git a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/FormAuthServletTest.java b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/FormAuthServletTest.java
new file mode 100644
index 0000000..9881c5f
--- /dev/null
+++ b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/FormAuthServletTest.java
@@ -0,0 +1,81 @@
+/*
+ * 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.tomee.security.servlet;
+
+import org.junit.Test;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.security.enterprise.authentication.mechanism.http.FormAuthenticationMechanismDefinition;
+import javax.security.enterprise.authentication.mechanism.http.LoginToContinue;
+import javax.servlet.ServletException;
+import javax.servlet.annotation.HttpConstraint;
+import javax.servlet.annotation.ServletSecurity;
+import javax.servlet.annotation.WebServlet;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.client.ClientBuilder;
+import java.io.IOException;
+
+import static org.junit.Assert.assertEquals;
+
+public class FormAuthServletTest extends AbstractTomEESecurityTest {
+    @Test
+    public void authenticate() throws Exception {
+        final String servlet = "http://localhost:" + container.getConfiguration().getHttpPort() + "/form";
+        assertEquals(200, ClientBuilder.newBuilder().build()
+                                       .target(servlet)
+                                       .request()
+                                       .get().getStatus());
+    }
+
+    @ApplicationScoped
+    @FormAuthenticationMechanismDefinition(
+            loginToContinue = @LoginToContinue()
+    )
+    public static class ApplicationAuthentication {
+
+    }
+
+    @WebServlet(urlPatterns = "/login")
+    public static class LoginServlet extends HttpServlet {
+        @Override
+        protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
+                throws ServletException, IOException {
+
+        }
+    }
+
+    @WebServlet(urlPatterns = "/login-error")
+    public static class ErrorServlet extends HttpServlet {
+        @Override
+        protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
+                throws ServletException, IOException {
+
+        }
+    }
+
+    @WebServlet(urlPatterns = "/form")
+    @ServletSecurity(@HttpConstraint(rolesAllowed = "tomcat"))
+    public static class TestServlet extends HttpServlet {
+        @Override
+        protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
+                throws ServletException, IOException {
+            resp.getWriter().write("ok!");
+        }
+    }
+}


[tomee] 07/48: TOMEE-2365 - Implemented default IdentifyStoreHandler.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit c33ad08351f9e95f7ae1096d71015bd56076e0a3
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Tue Dec 18 17:37:35 2018 +0000

    TOMEE-2365 - Implemented default IdentifyStoreHandler.
---
 .../identitystore/TomEEIdentityStoreHandler.java   | 103 +++++++++++++++++++++
 1 file changed, 103 insertions(+)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/identitystore/TomEEIdentityStoreHandler.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/identitystore/TomEEIdentityStoreHandler.java
new file mode 100644
index 0000000..8b85513
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/identitystore/TomEEIdentityStoreHandler.java
@@ -0,0 +1,103 @@
+/*
+ * 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.tomee.security.identitystore;
+
+import javax.annotation.PostConstruct;
+import javax.enterprise.context.ApplicationScoped;
+import javax.enterprise.inject.Instance;
+import javax.inject.Inject;
+import javax.security.enterprise.credential.Credential;
+import javax.security.enterprise.identitystore.CredentialValidationResult;
+import javax.security.enterprise.identitystore.IdentityStore;
+import javax.security.enterprise.identitystore.IdentityStoreHandler;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import static javax.security.enterprise.identitystore.CredentialValidationResult.INVALID_RESULT;
+import static javax.security.enterprise.identitystore.CredentialValidationResult.NOT_VALIDATED_RESULT;
+import static javax.security.enterprise.identitystore.CredentialValidationResult.Status.VALID;
+import static javax.security.enterprise.identitystore.IdentityStore.ValidationType.PROVIDE_GROUPS;
+import static javax.security.enterprise.identitystore.IdentityStore.ValidationType.VALIDATE;
+
+@ApplicationScoped
+public class TomEEIdentityStoreHandler implements IdentityStoreHandler {
+    @Inject
+    private Instance<IdentityStore> identityStores;
+
+    private List<IdentityStore> authenticationStores;
+    private List<IdentityStore> authorizationStores;
+
+    @PostConstruct
+    private void init() {
+        authenticationStores =
+                identityStores.stream()
+                              .filter(i -> i.validationTypes().contains(VALIDATE))
+                              .sorted(Comparator.comparing(IdentityStore::priority))
+                              .collect(Collectors.toList());
+
+        authorizationStores =
+                identityStores.stream()
+                              .filter(i -> i.validationTypes().contains(PROVIDE_GROUPS))
+                              .filter(i -> !i.validationTypes().contains(VALIDATE))
+                              .sorted(Comparator.comparing(IdentityStore::priority))
+                              .collect(Collectors.toList());
+    }
+
+    @Override
+    public CredentialValidationResult validate(final Credential credential) {
+        if (authenticationStores.isEmpty()) {
+            return NOT_VALIDATED_RESULT;
+        }
+
+        CredentialValidationResult validationResult = null;
+        IdentityStore authorizedStore = null;
+        for (final IdentityStore identityStore : identityStores) {
+            validationResult = identityStore.validate(credential);
+            if (validationResult.getStatus().equals(VALID)) {
+                authorizedStore = identityStore;
+                break;
+            }
+        }
+
+        if (authorizedStore == null) {
+            return INVALID_RESULT;
+        }
+
+        final Set<String> groups = new HashSet<>();
+        if (authorizedStore.validationTypes().contains(PROVIDE_GROUPS)) {
+            groups.addAll(authorizedStore.getCallerGroups(validationResult));
+        }
+
+        final CredentialValidationResult authorizedValidationResult = validationResult;
+        final Set<String> additionalGroups =
+                authorizationStores.stream()
+                                   .map(as -> as.getCallerGroups(authorizedValidationResult))
+                                   .flatMap(Collection::stream)
+                                   .collect(Collectors.toSet());
+        groups.addAll(additionalGroups);
+
+        return new CredentialValidationResult(authorizedValidationResult.getIdentityStoreId(),
+                                              authorizedValidationResult.getCallerPrincipal(),
+                                              authorizedValidationResult.getCallerDn(),
+                                              authorizedValidationResult.getCallerUniqueId(),
+                                              groups);
+    }
+}


[tomee] 06/48: TOMEE-2365 - Added IdentityStore API.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit 7aa11b3e5f2536a99cfa43a3fe2699509088fe73
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Tue Dec 18 16:02:10 2018 +0000

    TOMEE-2365 - Added IdentityStore API.
---
 .../enterprise/identitystore/IdentityStore.java    | 33 ++++++++++++++++++++++
 .../identitystore/IdentityStoreHandler.java        | 23 +++++++++++++++
 2 files changed, 56 insertions(+)

diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/IdentityStore.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/IdentityStore.java
new file mode 100644
index 0000000..badb400
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/IdentityStore.java
@@ -0,0 +1,33 @@
+/*
+ * 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 javax.security.enterprise.identitystore;
+
+import javax.security.enterprise.credential.Credential;
+import java.util.Set;
+
+public interface IdentityStore {
+
+    enum ValidationType { VALIDATE, PROVIDE_GROUPS }
+
+    CredentialValidationResult validate(Credential credential);
+
+    Set<String> getCallerGroups(CredentialValidationResult validationResult);
+
+    int priority();
+
+    Set<ValidationType> validationTypes();
+}
diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/IdentityStoreHandler.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/IdentityStoreHandler.java
new file mode 100644
index 0000000..4ce3049
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/IdentityStoreHandler.java
@@ -0,0 +1,23 @@
+/*
+ * 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 javax.security.enterprise.identitystore;
+
+import javax.security.enterprise.credential.Credential;
+
+public interface IdentityStoreHandler {
+    CredentialValidationResult validate(Credential credential);
+}


[tomee] 36/48: TOMEE-2365 - Final step of form authentication. Retrieve original request and authentication data and pass it to the original requested resource.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit e635b265a610e6196c329a36972f5c4bbc6d9f48
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Fri Dec 28 14:58:24 2018 +0000

    TOMEE-2365 - Final step of form authentication. Retrieve original request and authentication data and pass it to the original requested resource.
---
 .../security/cdi/LoginToContinueInterceptor.java   | 20 +++++++++++--
 .../security/http/LoginToContinueMechanism.java    |  9 ++++++
 .../security/http/SavedHttpServletRequest.java     | 34 ++++++++++++++++++++++
 .../security/servlet/FormAuthServletTest.java      |  5 ++--
 4 files changed, 63 insertions(+), 5 deletions(-)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/LoginToContinueInterceptor.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/LoginToContinueInterceptor.java
index 1e0b0f3..612f779 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/LoginToContinueInterceptor.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/LoginToContinueInterceptor.java
@@ -17,6 +17,8 @@
 package org.apache.tomee.security.cdi;
 
 import org.apache.tomee.security.http.LoginToContinueMechanism;
+import org.apache.tomee.security.http.SavedAuthentication;
+import org.apache.tomee.security.http.SavedHttpServletRequest;
 import org.apache.tomee.security.http.SavedRequest;
 
 import javax.annotation.Priority;
@@ -33,6 +35,8 @@ import java.util.Arrays;
 import static javax.interceptor.Interceptor.Priority.PLATFORM_BEFORE;
 import static javax.security.enterprise.AuthenticationStatus.SEND_FAILURE;
 import static javax.security.enterprise.AuthenticationStatus.SUCCESS;
+import static org.apache.tomee.security.http.LoginToContinueMechanism.clearRequestAndAuthentication;
+import static org.apache.tomee.security.http.LoginToContinueMechanism.getAuthentication;
 import static org.apache.tomee.security.http.LoginToContinueMechanism.getRequest;
 import static org.apache.tomee.security.http.LoginToContinueMechanism.hasAuthentication;
 import static org.apache.tomee.security.http.LoginToContinueMechanism.hasRequest;
@@ -127,10 +131,20 @@ public class LoginToContinueInterceptor {
         }
 
         if (isOnOriginalURLAfterAuthenticate(httpMessageContext)) {
-            return null;
+            final SavedRequest savedRequest = getRequest(httpMessageContext.getRequest());
+            final SavedAuthentication savedAuthentication = getAuthentication(httpMessageContext.getRequest());
+
+            clearRequestAndAuthentication(httpMessageContext.getRequest());
+
+            final SavedHttpServletRequest savedHttpServletRequest =
+                    new SavedHttpServletRequest(httpMessageContext.getRequest(), savedRequest);
+
+            return httpMessageContext.withRequest(savedHttpServletRequest)
+                                     .notifyContainerAboutLogin(savedAuthentication.getPrincipal(),
+                                                                savedAuthentication.getGroups());
         }
 
-        return null;
+        return (AuthenticationStatus) invocationContext.proceed();
     }
 
     private boolean isOnInitialProtectedURL(final HttpMessageContext httpMessageContext) {
@@ -142,7 +156,7 @@ public class LoginToContinueInterceptor {
     }
 
     private boolean isOnOriginalURLAfterAuthenticate(final HttpMessageContext httpMessageContext) {
-        return false;
+        return hasRequest(httpMessageContext.getRequest()) && hasAuthentication(httpMessageContext.getRequest());
     }
 
     private LoginToContinue getLoginToContinue(final InvocationContext invocationContext) {
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/LoginToContinueMechanism.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/LoginToContinueMechanism.java
index e67b4b4..7871595 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/LoginToContinueMechanism.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/LoginToContinueMechanism.java
@@ -132,4 +132,13 @@ public interface LoginToContinueMechanism {
     static boolean hasAuthentication(final HttpServletRequest request) {
         return request.getSession().getAttribute(AUTHENTICATION) != null;
     }
+
+    static SavedAuthentication getAuthentication(final HttpServletRequest request) {
+        return (SavedAuthentication) request.getSession().getAttribute(AUTHENTICATION);
+    }
+
+    static void clearRequestAndAuthentication(final HttpServletRequest request) {
+        request.getSession().removeAttribute(ORIGINAL_REQUEST);
+        request.getSession().removeAttribute(AUTHENTICATION);
+    }
 }
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/SavedHttpServletRequest.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/SavedHttpServletRequest.java
new file mode 100644
index 0000000..5a91d5b
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/SavedHttpServletRequest.java
@@ -0,0 +1,34 @@
+/*
+ * 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.tomee.security.http;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletRequestWrapper;
+
+public class SavedHttpServletRequest extends HttpServletRequestWrapper {
+    private final SavedRequest savedRequest;
+
+    public SavedHttpServletRequest(final HttpServletRequest request, final SavedRequest savedRequest) {
+        super(request);
+        this.savedRequest = savedRequest;
+    }
+
+    @Override
+    public String getMethod() {
+        return savedRequest.getMethod();
+    }
+}
diff --git a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/FormAuthServletTest.java b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/FormAuthServletTest.java
index f006388..8a63dd6 100644
--- a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/FormAuthServletTest.java
+++ b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/FormAuthServletTest.java
@@ -48,8 +48,9 @@ public class FormAuthServletTest extends AbstractTomEESecurityTest {
         login.getInputByName("j_username").setValueAttribute("tomcat");
         login.getInputByName("j_password").setValueAttribute("tomcat");
 
-        final HtmlPage submit = login.getInputByName("submit").click();
-        System.out.println("submit.toString() = " + submit.toString());
+        final Page result = login.getInputByName("submit").click();
+        assertEquals(200, result.getWebResponse().getStatusCode());
+        assertEquals("ok!", result.getWebResponse().getContentAsString());
     }
 
     @ApplicationScoped


[tomee] 14/48: TOMEE-2365 - Fixed Authorization header read.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit 839c85e3f94237ae31e37f3bb0b6ab5e44f0b96a
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Mon Dec 24 18:18:37 2018 +0000

    TOMEE-2365 - Fixed Authorization header read.
---
 .../org/apache/tomee/security/cdi/BasicAuthenticationMechanism.java   | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/BasicAuthenticationMechanism.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/BasicAuthenticationMechanism.java
index 8f433fa..ba7adbd 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/BasicAuthenticationMechanism.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/BasicAuthenticationMechanism.java
@@ -28,9 +28,9 @@ import javax.security.enterprise.credential.BasicAuthenticationCredential;
 import javax.security.enterprise.identitystore.CredentialValidationResult;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
-import javax.ws.rs.core.HttpHeaders;
 
 import static javax.security.enterprise.identitystore.CredentialValidationResult.Status.VALID;
+import static javax.ws.rs.core.HttpHeaders.AUTHORIZATION;
 
 @ApplicationScoped
 public class BasicAuthenticationMechanism implements HttpAuthenticationMechanism {
@@ -49,7 +49,7 @@ public class BasicAuthenticationMechanism implements HttpAuthenticationMechanism
 
         try {
             final CredentialValidationResult result =
-                    identityStoreHandler.validate(new BasicAuthenticationCredential(HttpHeaders.AUTHORIZATION));
+                    identityStoreHandler.validate(new BasicAuthenticationCredential(request.getHeader(AUTHORIZATION)));
 
             if (result.getStatus().equals(VALID)) {
                 return httpMessageContext.notifyContainerAboutLogin(result);


[tomee] 13/48: TOMEE-2365 - Basic Auth test.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit a6b99d9775d6788c7bc4c49efe1b20311fb077d5
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Mon Dec 24 18:18:04 2018 +0000

    TOMEE-2365 - Basic Auth test.
---
 .../tomee/security/client/BasicAuthFilter.java     | 35 ++++++++++++++++++++++
 .../tomee/security/servlet/SimpleServletTest.java  | 19 +++++++++---
 2 files changed, 50 insertions(+), 4 deletions(-)

diff --git a/tomee/tomee-security/src/test/java/org/apache/tomee/security/client/BasicAuthFilter.java b/tomee/tomee-security/src/test/java/org/apache/tomee/security/client/BasicAuthFilter.java
new file mode 100644
index 0000000..16d6322
--- /dev/null
+++ b/tomee/tomee-security/src/test/java/org/apache/tomee/security/client/BasicAuthFilter.java
@@ -0,0 +1,35 @@
+/*
+ * 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.tomee.security.client;
+
+import javax.ws.rs.client.ClientRequestContext;
+import javax.ws.rs.client.ClientRequestFilter;
+import java.io.IOException;
+import java.util.Base64;
+
+import static javax.ws.rs.core.HttpHeaders.AUTHORIZATION;
+
+public class BasicAuthFilter implements ClientRequestFilter {
+    @Override
+    public void filter(final ClientRequestContext requestContext) throws IOException {
+        requestContext.getHeaders().add(AUTHORIZATION, basicAuth("tomcat", "tomcat"));
+    }
+
+    private String basicAuth(final String username, final String password) {
+        return "Basic " + new String(Base64.getEncoder().encode((username + ":" + password).getBytes()));
+    }
+}
diff --git a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java
index e645971..2a70385 100644
--- a/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java
+++ b/tomee/tomee-security/src/test/java/org/apache/tomee/security/servlet/SimpleServletTest.java
@@ -16,20 +16,25 @@
  */
 package org.apache.tomee.security.servlet;
 
-import org.apache.openejb.loader.IO;
 import org.apache.openejb.loader.JarLocation;
 import org.apache.openejb.util.NetworkUtil;
 import org.apache.tomee.embedded.Configuration;
 import org.apache.tomee.embedded.Container;
+import org.apache.tomee.security.client.BasicAuthFilter;
 import org.junit.Test;
 
+import javax.security.enterprise.authentication.mechanism.http.BasicAuthenticationMechanismDefinition;
 import javax.servlet.ServletException;
+import javax.servlet.annotation.HttpConstraint;
+import javax.servlet.annotation.ServletSecurity;
 import javax.servlet.annotation.WebServlet;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.client.Client;
+import javax.ws.rs.client.ClientBuilder;
+import javax.ws.rs.core.Response;
 import java.io.IOException;
-import java.net.URL;
 
 import static org.junit.Assert.assertEquals;
 
@@ -45,12 +50,18 @@ public class SimpleServletTest {
                         JarLocation.jarLocation(SimpleServletTest.class),
                         JarLocation.jarLocation(TomEESecurityServletContainerInitializer.class))) {
 
-            assertEquals("ok!", IO.slurp(
-                    new URL("http://localhost:" + container.getConfiguration().getHttpPort() + "/servlet")));
+            final Client client = ClientBuilder.newBuilder().register(new BasicAuthFilter()).build();
+            final Response response =
+                    client.target("http://localhost:" + container.getConfiguration().getHttpPort() + "/servlet")
+                          .request()
+                          .get();
+            assertEquals(200, response.getStatus());
         }
     }
 
     @WebServlet(urlPatterns = "/servlet")
+    @ServletSecurity(@HttpConstraint(rolesAllowed = "role"))
+    @BasicAuthenticationMechanismDefinition
     public static class TestServlet extends HttpServlet {
         @Override
         protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)


[tomee] 33/48: TOMEE-2365 - Save original request on first form login step.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit 199b35223e1527377b52650557c75d2a135eb069
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Fri Dec 28 10:57:41 2018 +0000

    TOMEE-2365 - Save original request on first form login step.
---
 .../security/cdi/LoginToContinueInterceptor.java   | 17 +++---
 .../security/http/LoginToContinueMechanism.java    | 68 ++++++++++++++++++++++
 2 files changed, 78 insertions(+), 7 deletions(-)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/LoginToContinueInterceptor.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/LoginToContinueInterceptor.java
index d35be0a..1895689 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/LoginToContinueInterceptor.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/LoginToContinueInterceptor.java
@@ -22,7 +22,6 @@ import javax.annotation.Priority;
 import javax.interceptor.AroundInvoke;
 import javax.interceptor.Interceptor;
 import javax.interceptor.InvocationContext;
-import javax.security.enterprise.AuthenticationException;
 import javax.security.enterprise.AuthenticationStatus;
 import javax.security.enterprise.authentication.mechanism.http.HttpMessageContext;
 import javax.security.enterprise.authentication.mechanism.http.LoginToContinue;
@@ -31,6 +30,8 @@ import javax.servlet.http.HttpServletResponse;
 import java.util.Arrays;
 
 import static javax.interceptor.Interceptor.Priority.PLATFORM_BEFORE;
+import static org.apache.tomee.security.http.LoginToContinueMechanism.isOriginalRequestInSession;
+import static org.apache.tomee.security.http.LoginToContinueMechanism.saveRequest;
 
 @LoginToContinue
 @Interceptor
@@ -51,7 +52,7 @@ public class LoginToContinueInterceptor {
     }
 
     private AuthenticationStatus validateRequest(final InvocationContext invocationContext)
-            throws AuthenticationException {
+            throws Exception {
 
         final HttpMessageContext httpMessageContext = (HttpMessageContext) invocationContext.getParameters()[2];
         clearStaleState(httpMessageContext);
@@ -74,11 +75,13 @@ public class LoginToContinueInterceptor {
 
     private AuthenticationStatus processContainerInitiatedAuthentication(
             final InvocationContext invocationContext,
-            final HttpMessageContext httpMessageContext) {
+            final HttpMessageContext httpMessageContext)
+            throws Exception {
 
         if (isOnInitialProtectedURL(httpMessageContext)) {
-            final LoginToContinue loginToContinue = getLoginToContinue(invocationContext);
+            saveRequest(httpMessageContext.getRequest());
 
+            final LoginToContinue loginToContinue = getLoginToContinue(invocationContext);
             if (loginToContinue.useForwardToLogin()) {
                 return httpMessageContext.forward(loginToContinue.loginPage());
             } else {
@@ -86,7 +89,7 @@ public class LoginToContinueInterceptor {
             }
         }
 
-        if (isOnOnLoginPostback(httpMessageContext)) {
+        if (isOnLoginPostback(httpMessageContext)) {
             return null;
         }
 
@@ -98,10 +101,10 @@ public class LoginToContinueInterceptor {
     }
 
     private boolean isOnInitialProtectedURL(final HttpMessageContext httpMessageContext) {
-        return httpMessageContext.isProtected();
+        return httpMessageContext.isProtected() && !isOriginalRequestInSession(httpMessageContext.getRequest());
     }
 
-    private boolean isOnOnLoginPostback(final HttpMessageContext httpMessageContext) {
+    private boolean isOnLoginPostback(final HttpMessageContext httpMessageContext) {
         return false;
     }
 
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/LoginToContinueMechanism.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/LoginToContinueMechanism.java
index fe5fccd..482bae6 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/LoginToContinueMechanism.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/http/LoginToContinueMechanism.java
@@ -16,8 +16,76 @@
  */
 package org.apache.tomee.security.http;
 
+import org.apache.catalina.authenticator.SavedRequest;
+import org.apache.tomcat.util.buf.ByteChunk;
+
 import javax.security.enterprise.authentication.mechanism.http.LoginToContinue;
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletRequest;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Enumeration;
+import java.util.Locale;
 
 public interface LoginToContinueMechanism {
+    int MAX_SAVE_POST_SIZE = 4 * 1024;
+
+    String ORIGINAL_REQUEST = "org.apache.tomee.security.request.original";
+
     LoginToContinue getLoginToContinue();
+
+    static void saveRequest(final HttpServletRequest request) throws IOException {
+        SavedRequest saved = new SavedRequest();
+        Cookie cookies[] = request.getCookies();
+        if (cookies != null) {
+            for (int i = 0; i < cookies.length; i++) {
+                saved.addCookie(cookies[i]);
+            }
+        }
+        Enumeration<String> names = request.getHeaderNames();
+        while (names.hasMoreElements()) {
+            String name = names.nextElement();
+            Enumeration<String> values = request.getHeaders(name);
+            while (values.hasMoreElements()) {
+                String value = values.nextElement();
+                saved.addHeader(name, value);
+            }
+        }
+        Enumeration<Locale> locales = request.getLocales();
+        while (locales.hasMoreElements()) {
+            Locale locale = locales.nextElement();
+            saved.addLocale(locale);
+        }
+
+        int maxSavePostSize = MAX_SAVE_POST_SIZE;
+        if (maxSavePostSize != 0) {
+            ByteChunk body = new ByteChunk();
+            body.setLimit(maxSavePostSize);
+
+            byte[] buffer = new byte[4096];
+            int bytesRead;
+            InputStream is = request.getInputStream();
+
+            while ( (bytesRead = is.read(buffer) ) >= 0) {
+                body.append(buffer, 0, bytesRead);
+            }
+
+            // Only save the request body if there is something to save
+            if (body.getLength() > 0) {
+                saved.setContentType(request.getContentType());
+                saved.setBody(body);
+            }
+        }
+
+        saved.setMethod(request.getMethod());
+        saved.setQueryString(request.getQueryString());
+        saved.setRequestURI(request.getRequestURI());
+
+        // Stash the SavedRequest in our session for later use
+        request.getSession().setAttribute(ORIGINAL_REQUEST, saved);
+    }
+
+    static boolean isOriginalRequestInSession(final HttpServletRequest request) {
+        return request.getSession().getAttribute(ORIGINAL_REQUEST) != null;
+    }
 }


[tomee] 42/48: TOMEE-2365 - Values for layer and appContext.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit 99d6f10fbd213d6bb857c2aae4a7e653faf2995a
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Tue Jan 8 15:34:52 2019 +0000

    TOMEE-2365 - Values for layer and appContext.
---
 .../TomEESecurityServletContainerInitializer.java      | 18 +++++++++---------
 1 file changed, 9 insertions(+), 9 deletions(-)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/servlet/TomEESecurityServletContainerInitializer.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/servlet/TomEESecurityServletContainerInitializer.java
index 6dc9b25..fcf8452 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/servlet/TomEESecurityServletContainerInitializer.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/servlet/TomEESecurityServletContainerInitializer.java
@@ -20,23 +20,23 @@ import org.apache.tomee.security.cdi.TomEESecurityExtension;
 import org.apache.tomee.security.provider.TomEESecurityAuthConfigProvider;
 
 import javax.enterprise.inject.spi.CDI;
-import javax.inject.Inject;
 import javax.security.auth.message.config.AuthConfigFactory;
 import javax.servlet.ServletContainerInitializer;
 import javax.servlet.ServletContext;
 import javax.servlet.ServletException;
-import java.util.Optional;
 import java.util.Set;
 
 public class TomEESecurityServletContainerInitializer implements ServletContainerInitializer {
     @Override
     public void onStartup(final Set<Class<?>> c, final ServletContext ctx) throws ServletException {
-        Optional.ofNullable(CDI.current().getBeanManager().getExtension(TomEESecurityExtension.class))
-                .map(TomEESecurityExtension::hasAuthenticationMechanisms)
-                .filter(has -> has.equals(true))
-                .ifPresent(has -> AuthConfigFactory.getFactory()
-                                                   .registerConfigProvider(new TomEESecurityAuthConfigProvider(),
-                                                                           null, null,
-                                                                           "TomEE Security JSR-375"));
+        final TomEESecurityExtension securityExtension =
+                CDI.current().getBeanManager().getExtension(TomEESecurityExtension.class);
+
+        if (securityExtension.hasAuthenticationMechanisms()) {
+            AuthConfigFactory.getFactory()
+                             .registerConfigProvider(new TomEESecurityAuthConfigProvider(),
+                                                     "http", ctx.getVirtualServerName() + " " + ctx.getContextPath(),
+                                                     "TomEE Security JSR-375");
+        }
     }
 }


[tomee] 48/48: TOMEE-2365 - Fixed tests.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit 38ebd25299e1c9c0c011bfa55126a674e465997c
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Wed Jan 9 02:05:09 2019 +0000

    TOMEE-2365 - Fixed tests.
---
 .../org/apache/tomee/security/AbstractTomEESecurityTest.java  | 11 +----------
 1 file changed, 1 insertion(+), 10 deletions(-)

diff --git a/tomee/tomee-security/src/test/java/org/apache/tomee/security/AbstractTomEESecurityTest.java b/tomee/tomee-security/src/test/java/org/apache/tomee/security/AbstractTomEESecurityTest.java
index 1b8e90b..93572ca 100644
--- a/tomee/tomee-security/src/test/java/org/apache/tomee/security/AbstractTomEESecurityTest.java
+++ b/tomee/tomee-security/src/test/java/org/apache/tomee/security/AbstractTomEESecurityTest.java
@@ -20,9 +20,7 @@ import org.apache.openejb.loader.JarLocation;
 import org.apache.openejb.util.NetworkUtil;
 import org.apache.tomee.embedded.Configuration;
 import org.apache.tomee.embedded.Container;
-import org.apache.tomee.security.servlet.TomEESecurityServletContainerInitializer;
 import org.junit.AfterClass;
-import org.junit.Before;
 import org.junit.BeforeClass;
 
 public abstract class AbstractTomEESecurityTest {
@@ -36,9 +34,7 @@ public abstract class AbstractTomEESecurityTest {
                         .http(NetworkUtil.getNextAvailablePort())
                         .property("openejb.container.additional.exclude", "org.apache.tomee.security.")
                         .property("openejb.additional.include", "tomee-"))
-                .deployPathsAsWebapp(
-                        JarLocation.jarLocation(AbstractTomEESecurityTest.class),
-                        JarLocation.jarLocation(TomEESecurityServletContainerInitializer.class));
+                .deployPathsAsWebapp(JarLocation.jarLocation(AbstractTomEESecurityTest.class));
     }
 
     @AfterClass
@@ -46,11 +42,6 @@ public abstract class AbstractTomEESecurityTest {
         container.close();
     }
 
-    @Before
-    public void setUpBefore() throws Exception {
-        container.inject(this);
-    }
-
     protected String getAppUrl() {
         return "http://localhost:" + container.getConfiguration().getHttpPort();
     }


[tomee] 15/48: TOMEE-2365 - Additional bean to map Servlets to their Authentication Mechanisms.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit c57e6dd39b557c8a5d8af46fc35ebdb309170ede
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Mon Dec 24 18:19:54 2018 +0000

    TOMEE-2365 - Additional bean to map Servlets to their Authentication Mechanisms.
---
 .../tomee/security/cdi/TomEESecurityExtension.java | 30 ++++++++++++-
 ...curityServletAuthenticationMechanismMapper.java | 52 ++++++++++++++++++++++
 2 files changed, 80 insertions(+), 2 deletions(-)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityExtension.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityExtension.java
index 2f7bf04..3470bd2 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityExtension.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityExtension.java
@@ -16,12 +16,19 @@
  */
 package org.apache.tomee.security.cdi;
 
+import org.apache.tomee.security.identitystore.TomEEDefaultIdentityStore;
+import org.apache.tomee.security.identitystore.TomEEIdentityStoreHandler;
+
 import javax.enterprise.context.ApplicationScoped;
+import javax.enterprise.context.spi.CreationalContext;
 import javax.enterprise.event.Observes;
 import javax.enterprise.inject.Any;
 import javax.enterprise.inject.Default;
 import javax.enterprise.inject.spi.AfterBeanDiscovery;
 import javax.enterprise.inject.spi.AnnotatedType;
+import javax.enterprise.inject.spi.BeanAttributes;
+import javax.enterprise.inject.spi.BeanManager;
+import javax.enterprise.inject.spi.BeforeBeanDiscovery;
 import javax.enterprise.inject.spi.Extension;
 import javax.enterprise.inject.spi.ProcessAnnotatedType;
 import javax.security.enterprise.authentication.mechanism.http.BasicAuthenticationMechanismDefinition;
@@ -39,7 +46,18 @@ public class TomEESecurityExtension implements Extension {
         }
     }
 
-    void registerAuthenticationMechanism(@Observes final AfterBeanDiscovery afterBeanDiscovery) {
+    void observeBeforeBeanDiscovery(@Observes final BeforeBeanDiscovery beforeBeanDiscovery,
+                                    final BeanManager beanManager) {
+        if (basicAuthentication.isEmpty()) {
+            beforeBeanDiscovery.addAnnotatedType(
+                    beanManager.createAnnotatedType(TomEESecurityServletAuthenticationMechanismMapper.class));
+            beforeBeanDiscovery.addAnnotatedType(beanManager.createAnnotatedType(TomEEDefaultIdentityStore.class));
+            beforeBeanDiscovery.addAnnotatedType(beanManager.createAnnotatedType(TomEEIdentityStoreHandler.class));
+        }
+    }
+
+    void registerAuthenticationMechanism(@Observes final AfterBeanDiscovery afterBeanDiscovery,
+                                         final BeanManager beanManager) {
         if (!basicAuthentication.isEmpty()) {
             afterBeanDiscovery.addBean()
                .id(BasicAuthenticationMechanism.class.getName())
@@ -47,7 +65,15 @@ public class TomEESecurityExtension implements Extension {
                .types(Object.class, HttpAuthenticationMechanism.class, BasicAuthenticationMechanism.class)
                .qualifiers(Default.Literal.INSTANCE, Any.Literal.INSTANCE)
                .scope(ApplicationScoped.class)
-               .createWith(creationalContext -> new BasicAuthenticationMechanism());
+               .createWith((CreationalContext<BasicAuthenticationMechanism> creationalContext) -> {
+                   AnnotatedType<BasicAuthenticationMechanism> annotatedType =
+                           beanManager.createAnnotatedType(BasicAuthenticationMechanism.class);
+                   BeanAttributes<BasicAuthenticationMechanism> beanAttributes =
+                           beanManager.createBeanAttributes(annotatedType);
+                   return beanManager.createBean(beanAttributes, BasicAuthenticationMechanism.class,
+                                                 beanManager.getInjectionTargetFactory(annotatedType))
+                                     .create(creationalContext);
+               });
         }
     }
 }
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityServletAuthenticationMechanismMapper.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityServletAuthenticationMechanismMapper.java
new file mode 100644
index 0000000..bbad8ef
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/TomEESecurityServletAuthenticationMechanismMapper.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.tomee.security.cdi;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.enterprise.context.Initialized;
+import javax.enterprise.event.Observes;
+import javax.enterprise.inject.spi.CDI;
+import javax.security.enterprise.authentication.mechanism.http.BasicAuthenticationMechanismDefinition;
+import javax.security.enterprise.authentication.mechanism.http.HttpAuthenticationMechanism;
+import javax.servlet.ServletContext;
+import javax.servlet.ServletRegistration;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+@ApplicationScoped
+public class TomEESecurityServletAuthenticationMechanismMapper {
+    private final Map<String, HttpAuthenticationMechanism> servletAuthenticationMapper = new ConcurrentHashMap<>();
+
+    public void init(@Observes @Initialized(ApplicationScoped.class) final ServletContext context) {
+        final Map<String, ? extends ServletRegistration> servletRegistrations = context.getServletRegistrations();
+        servletRegistrations.forEach((servletName, servletRegistration) -> {
+            try {
+                final Class<?> servletClass = Thread.currentThread().getContextClassLoader().loadClass(servletName);
+                if (servletClass.isAnnotationPresent(BasicAuthenticationMechanismDefinition.class)) {
+                    servletAuthenticationMapper.put(servletName,
+                                                    CDI.current().select(BasicAuthenticationMechanism.class).get());
+                }
+            } catch (final ClassNotFoundException e) {
+                // Ignore
+            }
+        });
+    }
+
+    public HttpAuthenticationMechanism getCurrentAuthenticationMechanism(final String servletName) {
+        return servletAuthenticationMapper.get(servletName);
+    }
+}


[tomee] 05/48: TOMEE-2365 - Initial API code.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit dc81bb9dc9a1d47b2595025b825d0be78645d1c5
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Mon Dec 17 21:08:02 2018 +0000

    TOMEE-2365 - Initial API code.
---
 .../enterprise/AuthenticationException.java        |  39 +++++++
 .../security/enterprise/AuthenticationStatus.java  |  24 +++++
 .../javax/security/enterprise/CallerPrincipal.java |  35 ++++++
 .../mechanism/http/AuthenticationParameters.java   |  68 ++++++++++++
 .../BasicAuthenticationMechanismDefinition.java    |  29 +++++
 ...ustomFormAuthenticationMechanismDefinition.java |  31 ++++++
 .../FormAuthenticationMechanismDefinition.java     |  31 ++++++
 .../http/HttpAuthenticationMechanism.java          |  42 ++++++++
 .../mechanism/http/HttpMessageContext.java         |  77 +++++++++++++
 .../mechanism/http/LoginToContinue.java            |  44 ++++++++
 .../security/enterprise/credential/Credential.java |  29 +++++
 .../identitystore/CredentialValidationResult.java  | 119 +++++++++++++++++++++
 12 files changed, 568 insertions(+)

diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/AuthenticationException.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/AuthenticationException.java
new file mode 100644
index 0000000..e30ba20
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/AuthenticationException.java
@@ -0,0 +1,39 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package javax.security.enterprise;
+
+import java.security.GeneralSecurityException;
+
+public class AuthenticationException extends GeneralSecurityException {
+    private static final long serialVersionUID = 1L;
+
+    public AuthenticationException() {
+        super();
+    }
+
+    public AuthenticationException(String message) {
+        super(message);
+    }
+
+    public AuthenticationException(String message, Throwable cause) {
+        super(message, cause);
+    }
+
+    public AuthenticationException(Throwable cause) {
+        super(cause);
+    }
+}
diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/AuthenticationStatus.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/AuthenticationStatus.java
new file mode 100644
index 0000000..208eb59
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/AuthenticationStatus.java
@@ -0,0 +1,24 @@
+/*
+ * 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 javax.security.enterprise;
+
+public enum AuthenticationStatus {
+    NOT_DONE,
+    SEND_CONTINUE,
+    SUCCESS,
+    SEND_FAILURE
+}
diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/CallerPrincipal.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/CallerPrincipal.java
new file mode 100644
index 0000000..e02b801
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/CallerPrincipal.java
@@ -0,0 +1,35 @@
+/*
+ * 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 javax.security.enterprise;
+
+import java.io.Serializable;
+import java.security.Principal;
+
+public class CallerPrincipal implements Principal, Serializable {
+    private static final long serialVersionUID = -6951555039431667786L;
+
+    private final String name;
+
+    public CallerPrincipal(String name) {
+        this.name = name;
+    }
+
+    @Override
+    public String getName() {
+        return name;
+    }
+}
diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/AuthenticationParameters.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/AuthenticationParameters.java
new file mode 100644
index 0000000..ac03426
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/AuthenticationParameters.java
@@ -0,0 +1,68 @@
+/*
+ * 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 javax.security.enterprise.authentication.mechanism.http;
+
+import javax.security.enterprise.credential.Credential;
+
+public class AuthenticationParameters {
+    private Credential credential;
+    private boolean newAuthentication;
+    private boolean rememberMe;
+
+    public static AuthenticationParameters withParams() {
+        return new AuthenticationParameters();
+    }
+
+    public AuthenticationParameters credential(Credential credential) {
+        setCredential(credential);
+        return this;
+    }
+
+    public AuthenticationParameters newAuthentication(boolean newAuthentication) {
+        setNewAuthentication(newAuthentication);
+        return this;
+    }
+
+    public AuthenticationParameters rememberMe(boolean rememberMe) {
+        setRememberMe(rememberMe);
+        return this;
+    }
+
+    public Credential getCredential() {
+        return credential;
+    }
+
+    public void setCredential(Credential credential) {
+        this.credential = credential;
+    }
+
+    public boolean isNewAuthentication() {
+        return newAuthentication;
+    }
+
+    public void setNewAuthentication(boolean newAuthentication) {
+        this.newAuthentication = newAuthentication;
+    }
+
+    public boolean isRememberMe() {
+        return rememberMe;
+    }
+
+    public void setRememberMe(boolean rememberMe) {
+        this.rememberMe = rememberMe;
+    }
+}
diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/BasicAuthenticationMechanismDefinition.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/BasicAuthenticationMechanismDefinition.java
new file mode 100644
index 0000000..badf841
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/BasicAuthenticationMechanismDefinition.java
@@ -0,0 +1,29 @@
+/*
+ * 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 javax.security.enterprise.authentication.mechanism.http;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+@Retention(RUNTIME)
+@Target(TYPE)
+public @interface BasicAuthenticationMechanismDefinition {
+    String realmName() default "";
+}
diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/CustomFormAuthenticationMechanismDefinition.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/CustomFormAuthenticationMechanismDefinition.java
new file mode 100644
index 0000000..a3e981d
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/CustomFormAuthenticationMechanismDefinition.java
@@ -0,0 +1,31 @@
+/*
+ * 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 javax.security.enterprise.authentication.mechanism.http;
+
+import javax.enterprise.util.Nonbinding;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+@Retention(RUNTIME)
+@Target(TYPE)
+public @interface CustomFormAuthenticationMechanismDefinition {
+    @Nonbinding
+    LoginToContinue loginToContinue();
+}
diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/FormAuthenticationMechanismDefinition.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/FormAuthenticationMechanismDefinition.java
new file mode 100644
index 0000000..22b5cfe
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/FormAuthenticationMechanismDefinition.java
@@ -0,0 +1,31 @@
+/*
+ * 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 javax.security.enterprise.authentication.mechanism.http;
+
+import javax.enterprise.util.Nonbinding;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+@Retention(RUNTIME)
+@Target(TYPE)
+public @interface FormAuthenticationMechanismDefinition {
+    @Nonbinding
+    LoginToContinue loginToContinue();
+}
diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/HttpAuthenticationMechanism.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/HttpAuthenticationMechanism.java
new file mode 100644
index 0000000..03f7282
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/HttpAuthenticationMechanism.java
@@ -0,0 +1,42 @@
+/*
+ * 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 javax.security.enterprise.authentication.mechanism.http;
+
+import javax.security.enterprise.AuthenticationException;
+import javax.security.enterprise.AuthenticationStatus;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import static javax.security.enterprise.AuthenticationStatus.SUCCESS;
+
+public interface HttpAuthenticationMechanism {
+
+    AuthenticationStatus validateRequest(HttpServletRequest request, HttpServletResponse response,
+                                         HttpMessageContext httpMessageContext)
+            throws AuthenticationException;
+
+    default AuthenticationStatus secureResponse(HttpServletRequest request, HttpServletResponse response,
+                                                HttpMessageContext httpMessageContext)
+            throws AuthenticationException {
+        return SUCCESS;
+    }
+
+    default void cleanSubject(HttpServletRequest request, HttpServletResponse response,
+                              HttpMessageContext httpMessageContext) {
+        httpMessageContext.cleanClientSubject();
+    }
+}
diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/HttpMessageContext.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/HttpMessageContext.java
new file mode 100644
index 0000000..5fc4fb3
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/HttpMessageContext.java
@@ -0,0 +1,77 @@
+/*
+ * 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 javax.security.enterprise.authentication.mechanism.http;
+
+import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.message.MessageInfo;
+import javax.security.enterprise.AuthenticationStatus;
+import javax.security.enterprise.identitystore.CredentialValidationResult;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.security.Principal;
+import java.util.Set;
+
+public interface HttpMessageContext {
+    boolean isProtected();
+
+    boolean isAuthenticationRequest();
+
+    boolean isRegisterSession();
+
+    void setRegisterSession(String callerName, Set<String> groups);
+
+    void cleanClientSubject();
+
+    AuthenticationParameters getAuthParameters();
+
+    CallbackHandler getHandler();
+
+    MessageInfo getMessageInfo();
+
+    Subject getClientSubject();
+
+    HttpServletRequest getRequest();
+
+    void setRequest(HttpServletRequest request);
+
+    HttpMessageContext withRequest(HttpServletRequest request);
+
+    HttpServletResponse getResponse();
+
+    void setResponse(HttpServletResponse response);
+
+    AuthenticationStatus redirect(String location);
+
+    AuthenticationStatus forward(String path);
+
+    AuthenticationStatus responseUnauthorized();
+
+    AuthenticationStatus responseNotFound();
+
+    AuthenticationStatus notifyContainerAboutLogin(String callername, Set<String> groups);
+
+    AuthenticationStatus notifyContainerAboutLogin(Principal principal, Set<String> groups);
+
+    AuthenticationStatus notifyContainerAboutLogin(CredentialValidationResult result);
+
+    AuthenticationStatus doNothing();
+
+    Principal getCallerPrincipal();
+
+    Set<String> getGroups();
+}
diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/LoginToContinue.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/LoginToContinue.java
new file mode 100644
index 0000000..e38f0d1
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/LoginToContinue.java
@@ -0,0 +1,44 @@
+/*
+ * 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 javax.security.enterprise.authentication.mechanism.http;
+
+import javax.enterprise.util.Nonbinding;
+import javax.interceptor.InterceptorBinding;
+import java.lang.annotation.Inherited;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+@Inherited
+@InterceptorBinding
+@Retention(RUNTIME)
+@Target(TYPE)
+public @interface LoginToContinue {
+    @Nonbinding
+    String loginPage() default "/login";
+
+    @Nonbinding
+    boolean useForwardToLogin() default true;
+
+    @Nonbinding
+    String useForwardToLoginExpression() default "";
+
+    @Nonbinding
+    String errorPage() default "/login-error";
+}
diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/credential/Credential.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/credential/Credential.java
new file mode 100644
index 0000000..2a063af
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/credential/Credential.java
@@ -0,0 +1,29 @@
+/*
+ * 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 javax.security.enterprise.credential;
+
+public interface Credential {
+    default boolean isCleared() {
+        return false;
+    }
+
+    default void clear() {}
+    
+    default boolean isValid() {
+        return true;
+    }
+}
diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/CredentialValidationResult.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/CredentialValidationResult.java
new file mode 100644
index 0000000..c24be15
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/CredentialValidationResult.java
@@ -0,0 +1,119 @@
+/*
+ * 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 javax.security.enterprise.identitystore;
+
+
+import javax.security.enterprise.CallerPrincipal;
+import java.util.HashSet;
+import java.util.Set;
+
+import static java.util.Collections.emptySet;
+import static java.util.Collections.unmodifiableSet;
+import static javax.security.enterprise.identitystore.CredentialValidationResult.Status.INVALID;
+import static javax.security.enterprise.identitystore.CredentialValidationResult.Status.NOT_VALIDATED;
+import static javax.security.enterprise.identitystore.CredentialValidationResult.Status.VALID;
+
+public class CredentialValidationResult {
+    public static final CredentialValidationResult INVALID_RESULT = new CredentialValidationResult(INVALID);
+    public static final CredentialValidationResult NOT_VALIDATED_RESULT = new CredentialValidationResult(NOT_VALIDATED);
+
+    private final Status status;
+    private final String storeId;
+    private final String callerDn;
+    private final String callerUniqueId;
+    private final CallerPrincipal callerPrincipal;
+    private final Set<String> groups;
+
+    public enum Status {
+        NOT_VALIDATED,
+        INVALID,
+        VALID
+    }
+
+    private CredentialValidationResult(Status status) {
+        this(status, null, null, null, null, null);
+    }
+
+    public CredentialValidationResult(String callerName) {
+        this(new CallerPrincipal(callerName), null);
+    }
+
+    public CredentialValidationResult(CallerPrincipal callerPrincipal) {
+        this(callerPrincipal, null);
+    }
+
+    public CredentialValidationResult(String callerName, Set<String> groups) {
+        this(new CallerPrincipal(callerName), groups);
+    }
+
+    public CredentialValidationResult(CallerPrincipal callerPrincipal, Set<String> groups) {
+        this(null, callerPrincipal, null, null, groups);
+    }
+
+    public CredentialValidationResult(String storeId, String callerName, String callerDn, String callerUniqueId,
+                                      Set<String> groups) {
+        this(storeId, new CallerPrincipal(callerName), callerDn, callerUniqueId, groups);
+    }
+
+    public CredentialValidationResult(String storeId, CallerPrincipal callerPrincipal, String callerDn,
+                                      String callerUniqueId, Set<String> groups) {
+        this(VALID, storeId, callerPrincipal, callerDn, callerUniqueId, groups);
+    }
+
+    private CredentialValidationResult(Status status, String storeId, CallerPrincipal callerPrincipal, String callerDn,
+                                       String callerUniqueId, Set<String> groups) {
+
+        if (status != VALID && (storeId != null || callerPrincipal != null ||
+                                callerDn != null || callerUniqueId != null || groups != null)) {
+            throw new IllegalArgumentException("Bad status");
+        }
+        if (status == VALID && (callerPrincipal == null || callerPrincipal.getName().trim().isEmpty())) {
+            throw new IllegalArgumentException("Null or empty CallerPrincipal");
+        }
+
+        this.status = status;
+        this.storeId = storeId;
+        this.callerPrincipal = callerPrincipal;
+        this.callerDn = callerDn;
+        this.callerUniqueId = callerUniqueId;
+        this.groups = groups != null ? unmodifiableSet(new HashSet<>(groups)) : emptySet();
+    }
+
+    public Status getStatus() {
+        return status;
+    }
+
+    public String getIdentityStoreId() {
+        return storeId;
+    }
+
+    public CallerPrincipal getCallerPrincipal() {
+        return callerPrincipal;
+    }
+
+    public String getCallerUniqueId() {
+        return callerUniqueId;
+    }
+
+    public String getCallerDn() {
+        return callerDn;
+    }
+
+    public Set<String> getCallerGroups() {
+        return groups;
+    }
+}


[tomee] 09/48: TOMEE-2365 - Added HttpMessageContext wrapper API.

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

radcortez pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/tomee.git

commit e753603b341dbf4b68d68258bb974d9f8e7d3090
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Tue Dec 18 18:55:39 2018 +0000

    TOMEE-2365 - Added HttpMessageContext wrapper API.
---
 .../mechanism/http/HttpMessageContextWrapper.java  | 159 +++++++++++++++++++++
 1 file changed, 159 insertions(+)

diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/HttpMessageContextWrapper.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/HttpMessageContextWrapper.java
new file mode 100644
index 0000000..137f11c
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/HttpMessageContextWrapper.java
@@ -0,0 +1,159 @@
+/*
+ * 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 javax.security.enterprise.authentication.mechanism.http;
+
+import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.message.MessageInfo;
+import javax.security.enterprise.AuthenticationStatus;
+import javax.security.enterprise.identitystore.CredentialValidationResult;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.security.Principal;
+import java.util.Set;
+
+public class HttpMessageContextWrapper implements HttpMessageContext {
+    private final HttpMessageContext httpMessageContext;
+
+    public HttpMessageContextWrapper(final HttpMessageContext httpMessageContext) {
+        this.httpMessageContext = httpMessageContext;
+    }
+
+    public HttpMessageContext getWrapped() {
+        return httpMessageContext;
+    }
+
+    @Override
+    public boolean isProtected() {
+        return getWrapped().isProtected();
+    }
+
+    @Override
+    public boolean isAuthenticationRequest() {
+        return getWrapped().isAuthenticationRequest();
+    }
+
+    @Override
+    public boolean isRegisterSession() {
+        return getWrapped().isRegisterSession();
+    }
+
+    @Override
+    public void setRegisterSession(final String callerName, final Set<String> groups) {
+        getWrapped().setRegisterSession(callerName, groups);
+    }
+
+    @Override
+    public void cleanClientSubject() {
+        getWrapped().cleanClientSubject();
+    }
+
+    @Override
+    public AuthenticationParameters getAuthParameters() {
+        return getWrapped().getAuthParameters();
+    }
+
+    @Override
+    public CallbackHandler getHandler() {
+        return getWrapped().getHandler();
+    }
+
+    @Override
+    public MessageInfo getMessageInfo() {
+        return getWrapped().getMessageInfo();
+    }
+
+    @Override
+    public Subject getClientSubject() {
+        return getWrapped().getClientSubject();
+    }
+
+    @Override
+    public HttpServletRequest getRequest() {
+        return getWrapped().getRequest();
+    }
+
+    @Override
+    public void setRequest(final HttpServletRequest request) {
+        getWrapped().setRequest(request);
+    }
+
+    @Override
+    public HttpMessageContext withRequest(final HttpServletRequest request) {
+        return getWrapped().withRequest(request);
+    }
+
+    @Override
+    public HttpServletResponse getResponse() {
+        return getWrapped().getResponse();
+    }
+
+    @Override
+    public void setResponse(final HttpServletResponse response) {
+        getWrapped().setResponse(response);
+    }
+
+    @Override
+    public AuthenticationStatus redirect(final String location) {
+        return getWrapped().redirect(location);
+    }
+
+    @Override
+    public AuthenticationStatus forward(final String path) {
+        return getWrapped().forward(path);
+    }
+
+    @Override
+    public AuthenticationStatus responseUnauthorized() {
+        return getWrapped().responseUnauthorized();
+    }
+
+    @Override
+    public AuthenticationStatus responseNotFound() {
+        return getWrapped().responseNotFound();
+    }
+
+    @Override
+    public AuthenticationStatus notifyContainerAboutLogin(final String callername, final Set<String> groups) {
+        return getWrapped().notifyContainerAboutLogin(callername, groups);
+    }
+
+    @Override
+    public AuthenticationStatus notifyContainerAboutLogin(final Principal principal, final Set<String> groups) {
+        return getWrapped().notifyContainerAboutLogin(principal, groups);
+    }
+
+    @Override
+    public AuthenticationStatus notifyContainerAboutLogin(final CredentialValidationResult result) {
+        return getWrapped().notifyContainerAboutLogin(result);
+    }
+
+    @Override
+    public AuthenticationStatus doNothing() {
+        return getWrapped().doNothing();
+    }
+
+    @Override
+    public Principal getCallerPrincipal() {
+        return getWrapped().getCallerPrincipal();
+    }
+
+    @Override
+    public Set<String> getGroups() {
+        return getWrapped().getGroups();
+    }
+}