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/17 13:10:14 UTC

[tomee] branch master updated (22e7c1e -> 0373733)

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 22e7c1e  Revert OpenAPI upgrade as it generates a StackOverflow
     new 5cfae0d  TOMEE-2365 - Fixed FormAuthenticationMechanism j_security_check resolution when added only to a servlet.
     new 84530e6  TOMEE-2365 - Added SecurityContext API.
     new 999e38e  TOMEE-2365 - Fixed DefaultAuthenticationMechanism init.
     new c7e8dd5  TOMEE-2365 - Implemented isAuthenticationRequest.
     new 58292c9  TOMEE-2365 - Implemented SecurityContext authenticate.
     new 2ec1224  TOMEE-2365 - Implemented SecurityContext getCallerPrincipal.
     new 348ee7d  TOMEE-2365 - Implemented SecurityContext isCallerInRole.
     new 0215b14  TOMEE-2365 - Added RememberMe API.
     new 9f482d3  TOMEE-2365 - Implemented RememberMeInterceptor.
     new 8c2ce3a  TOMEE-2365 - Added API annotations literals.
     new 776d975  TOMEE-2365 - Added API HttpAuthenticationMechanismWrapper.
     new aa09458  TOMEE-2365 - Added API CallerOnlyCredential.
     new fe8e59e  TOMEE-2365 - Added API for DatabaseIdentityStore.
     new f0a53f7  TOMEE-2365 - Added API for LdapIdentityStore.
     new c5d35aa  TOMEE-2365 - Added missing API for IdentityStore.
     new e85cce8  TOMEE-2365 - Restricted setDelegate method.
     new 0373733  TOMEE-2365 - Checkstyle issues.

The 17 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/tomee-security/pom.xml                       |   6 +
 .../javax/security/enterprise/SecurityContext.java |  30 ++-
 .../mechanism/http/AutoApplySession.java           |   7 +
 .../http/HttpAuthenticationMechanismWrapper.java   |  57 ++++++
 .../mechanism/http/LoginToContinue.java            |  80 ++++++++
 .../authentication/mechanism/http/RememberMe.java  | 216 +++++++++++++++++++++
 .../{Credential.java => CallerOnlyCredential.java} |  14 +-
 .../{Credential.java => RememberMeCredential.java} |  14 +-
 .../DatabaseIdentityStoreDefinition.java}          |  37 ++--
 ...reHandler.java => IdentityStorePermission.java} |  14 +-
 .../identitystore/IdentityStoreWrapper.java        |  41 ++--
 .../identitystore/LdapIdentityStoreDefinition.java |  85 ++++++++
 ...IdentityStoreHandler.java => PasswordHash.java} |  10 +-
 .../identitystore/Pbkdf2PasswordHash.java          |   6 +-
 ...reHandler.java => RememberMeIdentityStore.java} |  12 +-
 .../tomee/security/TomEESecurityContext.java       | 137 +++++++++++++
 .../cdi/DefaultAuthenticationMechanism.java        |   8 +-
 .../tomee/security/cdi/RememberMeInterceptor.java  | 151 ++++++++++++++
 .../tomee/security/cdi/TomEESecurityExtension.java |   4 +
 ...curityServletAuthenticationMechanismMapper.java |  11 +-
 .../security/http/TomEEHttpMessageContext.java     |   5 +-
 .../tomee/security/message/TomEEMessageInfo.java   |   2 +
 .../provider/TomEESecurityServerAuthModule.java    |   5 +-
 .../security/context/SecurityContextTest.java      | 194 ++++++++++++++++++
 .../security/servlet/FormAuthServletTest.java      |  12 +-
 25 files changed, 1055 insertions(+), 103 deletions(-)
 copy arquillian/arquillian-tomee-remote/src/test/java/org/apache/openejb/arquillian/TestServlet.java => tomee/tomee-security/src/main/java/javax/security/enterprise/SecurityContext.java (59%)
 create mode 100644 tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/HttpAuthenticationMechanismWrapper.java
 create mode 100644 tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/RememberMe.java
 copy tomee/tomee-security/src/main/java/javax/security/enterprise/credential/{Credential.java => CallerOnlyCredential.java} (79%)
 copy tomee/tomee-security/src/main/java/javax/security/enterprise/credential/{Credential.java => RememberMeCredential.java} (79%)
 copy tomee/tomee-security/src/main/java/javax/security/enterprise/{authentication/mechanism/http/LoginToContinue.java => identitystore/DatabaseIdentityStoreDefinition.java} (54%)
 copy tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/{IdentityStoreHandler.java => IdentityStorePermission.java} (70%)
 copy container/openejb-core/src/main/java/org/apache/openejb/config/ResourcesModule.java => tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/IdentityStoreWrapper.java (52%)
 create mode 100644 tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/LdapIdentityStoreDefinition.java
 copy tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/{IdentityStoreHandler.java => PasswordHash.java} (79%)
 copy container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/CmpEntityContainerInfo.java => tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/Pbkdf2PasswordHash.java (88%)
 copy tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/{IdentityStoreHandler.java => RememberMeIdentityStore.java} (69%)
 create mode 100644 tomee/tomee-security/src/main/java/org/apache/tomee/security/TomEESecurityContext.java
 create mode 100644 tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/RememberMeInterceptor.java
 create mode 100644 tomee/tomee-security/src/test/java/org/apache/tomee/security/context/SecurityContextTest.java


[tomee] 16/17: TOMEE-2365 - Restricted setDelegate method.

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 e85cce8c36a24443444cd9ef302b0fc4b146af35
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Thu Jan 17 12:30:56 2019 +0000

    TOMEE-2365 - Restricted setDelegate method.
---
 .../org/apache/tomee/security/cdi/DefaultAuthenticationMechanism.java   | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

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 0819eeb..3811e7f 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
@@ -54,7 +54,7 @@ public class DefaultAuthenticationMechanism implements HttpAuthenticationMechani
         delegate.cleanSubject(request, response, httpMessageContext);
     }
 
-    public void setDelegate(final HttpAuthenticationMechanism delegate) {
+    void setDelegate(final HttpAuthenticationMechanism delegate) {
         this.delegate = delegate;
     }
 


[tomee] 12/17: TOMEE-2365 - Added API CallerOnlyCredential.

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 aa0945802c395809a9f047b3708d70a149618cf1
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Thu Jan 17 12:29:18 2019 +0000

    TOMEE-2365 - Added API CallerOnlyCredential.
---
 .../credential/CallerOnlyCredential.java           | 29 ++++++++++++++++++++++
 1 file changed, 29 insertions(+)

diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/credential/CallerOnlyCredential.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/credential/CallerOnlyCredential.java
new file mode 100644
index 0000000..325a9e0
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/credential/CallerOnlyCredential.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 class CallerOnlyCredential implements Credential {
+    private final String caller;
+
+    public CallerOnlyCredential(String caller) {
+        this.caller = caller;
+    }
+
+    public String getCaller() {
+        return caller;
+    }
+}


[tomee] 09/17: TOMEE-2365 - Implemented RememberMeInterceptor.

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 9f482d3a45321f69cca202a51b6e65607fd25de4
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Wed Jan 16 18:47:17 2019 +0000

    TOMEE-2365 - Implemented RememberMeInterceptor.
---
 .../tomee/security/cdi/RememberMeInterceptor.java  | 151 +++++++++++++++++++++
 .../tomee/security/cdi/TomEESecurityExtension.java |   1 +
 2 files changed, 152 insertions(+)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/RememberMeInterceptor.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/RememberMeInterceptor.java
new file mode 100644
index 0000000..c8a1600
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/cdi/RememberMeInterceptor.java
@@ -0,0 +1,151 @@
+/*
+ * 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.enterprise.inject.Instance;
+import javax.enterprise.inject.Intercepted;
+import javax.enterprise.inject.spi.Bean;
+import javax.inject.Inject;
+import javax.interceptor.AroundInvoke;
+import javax.interceptor.Interceptor;
+import javax.interceptor.InvocationContext;
+import javax.security.enterprise.AuthenticationStatus;
+import javax.security.enterprise.CallerPrincipal;
+import javax.security.enterprise.authentication.mechanism.http.HttpMessageContext;
+import javax.security.enterprise.authentication.mechanism.http.RememberMe;
+import javax.security.enterprise.credential.RememberMeCredential;
+import javax.security.enterprise.identitystore.CredentialValidationResult;
+import javax.security.enterprise.identitystore.RememberMeIdentityStore;
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.util.Arrays;
+import java.util.Optional;
+import java.util.Set;
+
+import static javax.interceptor.Interceptor.Priority.PLATFORM_BEFORE;
+import static javax.security.enterprise.AuthenticationStatus.SUCCESS;
+import static javax.security.enterprise.identitystore.CredentialValidationResult.Status.VALID;
+
+@RememberMe
+@Interceptor
+@Priority(PLATFORM_BEFORE + 210)
+public class RememberMeInterceptor {
+    @Inject
+    @Intercepted
+    private Bean<?> httpMechanismBean;
+
+    @Inject
+    private Instance<RememberMeIdentityStore> rememberMeIdentityStore;
+
+    @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
+            })) {
+
+            if (rememberMeIdentityStore.isUnsatisfied()) {
+                throw new IllegalStateException("RememberMe annotated AuthenticationMechanism  " +
+                                                httpMechanismBean.getBeanClass() +
+                                                " required an implementation of RememberMeIndentityStore");
+            }
+
+            if (rememberMeIdentityStore.isAmbiguous()) {
+                throw new IllegalStateException(
+                        "Multiple implementations of RememberMeIndentityStore found. Only one should be supplied.");
+            }
+
+            return validateRequest(invocationContext);
+        }
+
+        if (invocationContext.getMethod().getName().equals("cleanSubject") &&
+            Arrays.equals(invocationContext.getMethod().getParameterTypes(), new Class<?>[]{
+                    HttpServletRequest.class,
+                    HttpServletResponse.class,
+                    HttpMessageContext.class
+            })) {
+            cleanSubject(invocationContext);
+        }
+
+        return invocationContext.proceed();
+    }
+
+    private AuthenticationStatus validateRequest(final InvocationContext invocationContext) throws Exception {
+        final HttpMessageContext httpMessageContext = (HttpMessageContext) invocationContext.getParameters()[2];
+
+        final RememberMe rememberMe = getRememberMe();
+        final Optional<Cookie> cookie = getCookie(httpMessageContext.getRequest(), rememberMe.cookieName());
+
+        if (cookie.isPresent()) {
+            final RememberMeCredential rememberMeCredential = new RememberMeCredential(cookie.get().getValue());
+            final CredentialValidationResult validate = rememberMeIdentityStore.get().validate(rememberMeCredential);
+
+            if (VALID.equals(validate.getStatus())) {
+                return httpMessageContext.notifyContainerAboutLogin(validate);
+            } else {
+                cookie.get().setMaxAge(0);
+                httpMessageContext.getResponse().addCookie(cookie.get());
+            }
+        }
+
+        final AuthenticationStatus status = (AuthenticationStatus) invocationContext.proceed();
+
+        if (SUCCESS.equals(status) && rememberMe.isRememberMe()) {
+            final CallerPrincipal principal = new CallerPrincipal(httpMessageContext.getCallerPrincipal().getName());
+            final Set<String> groups = httpMessageContext.getGroups();
+            final String loginToken = rememberMeIdentityStore.get().generateLoginToken(principal, groups);
+
+            final Cookie rememberMeCookie = new Cookie(rememberMe.cookieName(), loginToken);
+            rememberMeCookie.setMaxAge(rememberMe.cookieMaxAgeSeconds());
+            rememberMeCookie.setHttpOnly(rememberMe.cookieHttpOnly());
+            rememberMeCookie.setSecure(rememberMe.cookieSecureOnly());
+            httpMessageContext.getResponse().addCookie(rememberMeCookie);
+        }
+
+        return status;
+    }
+
+    private void cleanSubject(final InvocationContext invocationContext) throws Exception {
+        final HttpMessageContext httpMessageContext = (HttpMessageContext) invocationContext.getParameters()[2];
+
+        final RememberMe rememberMe = getRememberMe();
+        getCookie(httpMessageContext.getRequest(), rememberMe.cookieName())
+                .ifPresent(cookie -> {
+                    rememberMeIdentityStore.get().removeLoginToken(cookie.getValue());
+
+                    cookie.setMaxAge(0);
+                    httpMessageContext.getResponse().addCookie(cookie);
+                });
+
+        invocationContext.proceed();
+    }
+
+    private Optional<Cookie> getCookie(final HttpServletRequest request, final String name) {
+        return Arrays.stream(request.getCookies())
+                     .filter(c -> c.getName().equals(name))
+                     .findFirst();
+    }
+
+    private RememberMe getRememberMe() {
+        return Optional.ofNullable(httpMechanismBean.getBeanClass().getAnnotation(RememberMe.class))
+                       .orElseThrow(IllegalStateException::new);
+    }
+}
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 092bcff..d619d60 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
@@ -55,6 +55,7 @@ public class TomEESecurityExtension implements Extension {
         beforeBeanDiscovery.addAnnotatedType(beanManager.createAnnotatedType(TomEEIdentityStoreHandler.class));
 
         beforeBeanDiscovery.addAnnotatedType(beanManager.createAnnotatedType(AutoApplySessionInterceptor.class));
+        beforeBeanDiscovery.addAnnotatedType(beanManager.createAnnotatedType(RememberMeInterceptor.class));
         beforeBeanDiscovery.addAnnotatedType(beanManager.createAnnotatedType(LoginToContinueInterceptor.class));
 
         beforeBeanDiscovery.addAnnotatedType(beanManager.createAnnotatedType(TomEESecurityContext.class));


[tomee] 07/17: TOMEE-2365 - Implemented SecurityContext isCallerInRole.

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 348ee7dbec48cfce8e08eeb791c978b3518dd3b4
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Tue Jan 15 23:33:10 2019 +0000

    TOMEE-2365 - Implemented SecurityContext isCallerInRole.
---
 .../tomee/security/TomEESecurityContext.java       | 10 ++++--
 .../security/http/TomEEHttpMessageContext.java     |  7 +----
 .../security/context/SecurityContextTest.java      | 36 +++++++++++++++++++++-
 3 files changed, 43 insertions(+), 10 deletions(-)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/TomEESecurityContext.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/TomEESecurityContext.java
index 57df3f6..1ca2d89 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/TomEESecurityContext.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/TomEESecurityContext.java
@@ -18,6 +18,7 @@ package org.apache.tomee.security;
 
 import org.apache.catalina.authenticator.jaspic.CallbackHandlerImpl;
 import org.apache.catalina.connector.Request;
+import org.apache.catalina.realm.GenericPrincipal;
 import org.apache.openejb.loader.SystemInstance;
 import org.apache.openejb.spi.SecurityService;
 import org.apache.tomee.catalina.OpenEJBSecurityListener;
@@ -39,6 +40,7 @@ import javax.security.enterprise.authentication.mechanism.http.AuthenticationPar
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import java.security.Principal;
+import java.util.ArrayList;
 import java.util.Set;
 
 import static javax.security.auth.message.AuthStatus.SEND_CONTINUE;
@@ -68,7 +70,7 @@ public class TomEESecurityContext implements SecurityContext {
 
     @Override
     public boolean isCallerInRole(final String role) {
-        return false;
+        return securityService.isCallerInRole(role);
     }
 
     @Override
@@ -120,13 +122,15 @@ public class TomEESecurityContext implements SecurityContext {
         return serverAuthConfig.getAuthContext(null, null, null);
     }
 
-    public static void registerContainerAboutLogin(final Principal principal) {
+    public static void registerContainerAboutLogin(final Principal principal, final Set<String> groups) {
         final SecurityService securityService = SystemInstance.get().getComponent(SecurityService.class);
         if (TomcatSecurityService.class.isInstance(securityService)) {
             final TomcatSecurityService tomcatSecurityService = (TomcatSecurityService) securityService;
             final Request request = OpenEJBSecurityListener.requests.get();
+            final GenericPrincipal genericPrincipal =
+                    new GenericPrincipal(principal.getName(), null, new ArrayList<>(groups), principal);
             tomcatSecurityService.enterWebApp(request.getWrapper().getRealm(),
-                                              principal,
+                                              genericPrincipal,
                                               request.getWrapper().getRunAs());
         }
     }
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 16f3c29..ae77887 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,11 +17,6 @@
 package org.apache.tomee.security.http;
 
 import org.apache.catalina.authenticator.jaspic.MessageInfoImpl;
-import org.apache.catalina.connector.Request;
-import org.apache.openejb.loader.SystemInstance;
-import org.apache.openejb.spi.SecurityService;
-import org.apache.tomee.catalina.OpenEJBSecurityListener;
-import org.apache.tomee.catalina.TomcatSecurityService;
 import org.apache.tomee.security.TomEESecurityContext;
 import org.apache.tomee.security.message.TomEEMessageInfo;
 
@@ -209,7 +204,7 @@ public final class TomEEHttpMessageContext implements HttpMessageContext {
         this.principal = principal;
         this.groups = groups;
 
-        TomEESecurityContext.registerContainerAboutLogin(principal);
+        TomEESecurityContext.registerContainerAboutLogin(principal, groups);
 
         return SUCCESS;
     }
diff --git a/tomee/tomee-security/src/test/java/org/apache/tomee/security/context/SecurityContextTest.java b/tomee/tomee-security/src/test/java/org/apache/tomee/security/context/SecurityContextTest.java
index fe491fb..4e626bd 100644
--- a/tomee/tomee-security/src/test/java/org/apache/tomee/security/context/SecurityContextTest.java
+++ b/tomee/tomee-security/src/test/java/org/apache/tomee/security/context/SecurityContextTest.java
@@ -17,7 +17,6 @@
 package org.apache.tomee.security.context;
 
 import org.apache.tomee.security.AbstractTomEESecurityTest;
-import org.junit.Ignore;
 import org.junit.Test;
 
 import javax.inject.Inject;
@@ -73,6 +72,21 @@ public class SecurityContextTest extends AbstractTomEESecurityTest {
     }
 
     @Test
+    public void callerInRole() throws Exception {
+        final String servlet = getAppUrl() + "/securityContextRole";
+        final Response response = ClientBuilder.newBuilder()
+                                               .build()
+                                               .target(servlet)
+                                               .queryParam("username", "tomcat")
+                                               .queryParam("password", "tomcat")
+                                               .queryParam("role", "tomcat")
+                                               .request()
+                                               .get();
+        assertEquals(200, response.getStatus());
+        assertEquals("ok", response.readEntity(String.class));
+    }
+
+    @Test
     public void wrongPassword() throws Exception {
         final String servlet = getAppUrl() + "/securityContext";
         assertEquals(401, ClientBuilder.newBuilder().build()
@@ -127,6 +141,26 @@ public class SecurityContextTest extends AbstractTomEESecurityTest {
         }
     }
 
+    @WebServlet(urlPatterns = "/securityContextRole")
+    public static class RoleServlet extends HttpServlet {
+        @Inject
+        private SecurityContext securityContext;
+
+        @Override
+        protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
+                throws ServletException, IOException {
+
+            final AuthenticationParameters parameters =
+                    AuthenticationParameters.withParams()
+                                            .credential(new UsernamePasswordCredential(req.getParameter("username"),
+                                                                                       req.getParameter("password")))
+                                            .newAuthentication(true);
+
+            securityContext.authenticate(req, resp, parameters);
+
+            resp.getWriter().write(securityContext.isCallerInRole(req.getParameter("role")) ? "ok" : "nok");
+        }
+    }
 
     public static class SecurityContextHttpAuthenticationMechanism implements HttpAuthenticationMechanism {
         @Inject


[tomee] 04/17: TOMEE-2365 - Implemented isAuthenticationRequest.

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 c7e8dd522612dd7a2f72fe72fceab65c03abfe1e
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Mon Jan 14 16:34:41 2019 +0000

    TOMEE-2365 - Implemented isAuthenticationRequest.
---
 .../java/org/apache/tomee/security/http/TomEEHttpMessageContext.java    | 2 +-
 .../main/java/org/apache/tomee/security/message/TomEEMessageInfo.java   | 2 ++
 2 files changed, 3 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 0c2d898..28d0e4a 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
@@ -80,7 +80,7 @@ public final class TomEEHttpMessageContext implements HttpMessageContext {
 
     @Override
     public boolean isAuthenticationRequest() {
-        return false;
+        return Boolean.valueOf((String) messageInfo.getMap().getOrDefault(TomEEMessageInfo.AUTHENTICATE, "false"));
     }
 
     @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
index 1c4c989..c4817fe 100644
--- 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
@@ -24,6 +24,7 @@ import javax.servlet.http.HttpServletResponse;
 
 public class TomEEMessageInfo extends MessageInfoImpl {
     public static final String AUTH_PARAMS = "org.apache.tomee.security.context.authParams";
+    public static final String AUTHENTICATE = "org.apache.tomee.security.context.authenticate";
 
     public TomEEMessageInfo(final HttpServletRequest request,
                             final HttpServletResponse response,
@@ -37,5 +38,6 @@ public class TomEEMessageInfo extends MessageInfoImpl {
                             final AuthenticationParameters authParameters) {
         super(request, response, authMandatory);
         getMap().put(AUTH_PARAMS, authParameters);
+        getMap().put(AUTHENTICATE, Boolean.toString(true));
     }
 }


[tomee] 10/17: TOMEE-2365 - Added API annotations literals.

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 8c2ce3a491706307f836c1fdc0977f5d3c602c4b
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Thu Jan 17 12:27:50 2019 +0000

    TOMEE-2365 - Added API annotations literals.
---
 .../mechanism/http/AutoApplySession.java           |  8 +++
 .../mechanism/http/LoginToContinue.java            | 80 ++++++++++++++++++++++
 .../authentication/mechanism/http/RememberMe.java  |  1 +
 3 files changed, 89 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
index 6af744b..534e78f 100644
--- 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
@@ -16,6 +16,7 @@
  */
 package javax.security.enterprise.authentication.mechanism.http;
 
+import javax.enterprise.util.AnnotationLiteral;
 import javax.interceptor.InterceptorBinding;
 import java.lang.annotation.Inherited;
 import java.lang.annotation.Retention;
@@ -29,4 +30,11 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
 @Retention(RUNTIME)
 @Target(TYPE)
 public @interface AutoApplySession {
+    @SuppressWarnings("all")
+    public final static class Literal extends AnnotationLiteral<AutoApplySession> implements AutoApplySession {
+        private static final long serialVersionUID = 1L;
+
+        public static final Literal INSTANCE = new Literal();
+
+    }
 }
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
index e38f0d1..37faac9 100644
--- 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
@@ -16,6 +16,7 @@
  */
 package javax.security.enterprise.authentication.mechanism.http;
 
+import javax.enterprise.util.AnnotationLiteral;
 import javax.enterprise.util.Nonbinding;
 import javax.interceptor.InterceptorBinding;
 import java.lang.annotation.Inherited;
@@ -41,4 +42,83 @@ public @interface LoginToContinue {
 
     @Nonbinding
     String errorPage() default "/login-error";
+
+    @SuppressWarnings("all") final class Literal extends AnnotationLiteral<LoginToContinue> implements LoginToContinue {
+        private static final long serialVersionUID = 1L;
+
+        private final String loginPage;
+        private final boolean useForwardToLogin;
+        private final String useForwardToLoginExpression;
+        private final String errorPage;
+
+        public static LiteralBuilder builder() {
+            return new LiteralBuilder();
+        }
+
+        public static class LiteralBuilder {
+            private String loginPage = "/login";
+            private boolean useForwardToLogin = true;
+            private String useForwardToLoginExpression;
+            private String errorPage = "/login-error";
+
+            public LiteralBuilder loginPage(String loginPage) {
+                this.loginPage = loginPage;
+                return this;
+            }
+
+            public LiteralBuilder useForwardToLogin(boolean useForwardToLogin) {
+                this.useForwardToLogin = useForwardToLogin;
+                return this;
+            }
+
+            public LiteralBuilder useForwardToLoginExpression(String useForwardToLoginExpression) {
+                this.useForwardToLoginExpression = useForwardToLoginExpression;
+                return this;
+            }
+
+            public LiteralBuilder errorPage(String errorPage) {
+                this.errorPage = errorPage;
+                return this;
+            }
+
+            public Literal build() {
+                return new Literal(
+                        loginPage,
+                        useForwardToLogin,
+                        useForwardToLoginExpression,
+                        errorPage);
+            }
+        }
+
+        public Literal(String loginPage,
+                       boolean useForwardToLogin,
+                       String useForwardToLoginExpression,
+                       String errorPage) {
+            this.loginPage = loginPage;
+            this.useForwardToLogin = useForwardToLogin;
+            this.useForwardToLoginExpression = useForwardToLoginExpression;
+            this.errorPage = errorPage;
+        }
+
+        @Override
+        public String loginPage() {
+            return loginPage;
+        }
+
+        @Override
+        public boolean useForwardToLogin() {
+            return useForwardToLogin;
+        }
+
+        @Override
+        public String useForwardToLoginExpression() {
+            return useForwardToLoginExpression;
+        }
+
+        @Override
+        public String errorPage() {
+            return errorPage;
+        }
+
+    }
 }
diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/RememberMe.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/RememberMe.java
index e8b7e47..065e54f 100644
--- a/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/RememberMe.java
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/RememberMe.java
@@ -58,6 +58,7 @@ public @interface RememberMe {
     @Nonbinding
     String isRememberMeExpression() default "";
 
+    @SuppressWarnings("all")
     final class Literal extends AnnotationLiteral<RememberMe> implements RememberMe {
         private static final long serialVersionUID = 1L;
 


[tomee] 13/17: TOMEE-2365 - Added API for DatabaseIdentityStore.

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 fe8e59ed47688268cb90373cfca9f79be393c842
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Thu Jan 17 12:29:48 2019 +0000

    TOMEE-2365 - Added API for DatabaseIdentityStore.
---
 .../DatabaseIdentityStoreDefinition.java           | 51 ++++++++++++++++++++++
 .../enterprise/identitystore/PasswordHash.java     | 27 ++++++++++++
 .../identitystore/Pbkdf2PasswordHash.java          | 19 ++++++++
 3 files changed, 97 insertions(+)

diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/DatabaseIdentityStoreDefinition.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/DatabaseIdentityStoreDefinition.java
new file mode 100644
index 0000000..2f3faa6
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/DatabaseIdentityStoreDefinition.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 javax.security.enterprise.identitystore;
+
+import javax.security.enterprise.identitystore.IdentityStore.ValidationType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import static javax.security.enterprise.identitystore.IdentityStore.ValidationType.PROVIDE_GROUPS;
+import static javax.security.enterprise.identitystore.IdentityStore.ValidationType.VALIDATE;
+
+@Retention(RUNTIME)
+@Target(TYPE)
+public @interface DatabaseIdentityStoreDefinition {
+    String dataSourceLookup() default "java:comp/DefaultDataSource";
+
+    String callerQuery() default "";
+
+    String groupsQuery() default "";
+
+    Class<? extends PasswordHash> hashAlgorithm() default Pbkdf2PasswordHash.class;
+
+    String[] hashAlgorithmParameters() default {};
+
+    int priority() default 70;
+
+    String priorityExpression() default "";
+
+    ValidationType[] useFor() default {
+            VALIDATE,
+            PROVIDE_GROUPS
+    };
+
+    String useForExpression() default "";
+}
diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/PasswordHash.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/PasswordHash.java
new file mode 100644
index 0000000..8bd5bdf
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/PasswordHash.java
@@ -0,0 +1,27 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     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 java.util.Map;
+
+public interface PasswordHash {
+    default void initialize(Map<String, String> parameters) {}
+
+    String generate(char[] password);
+
+    boolean verify(char[] password, String hashedPassword);
+}
diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/Pbkdf2PasswordHash.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/Pbkdf2PasswordHash.java
new file mode 100644
index 0000000..9ed286f
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/Pbkdf2PasswordHash.java
@@ -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.
+ */
+package javax.security.enterprise.identitystore;
+
+public interface Pbkdf2PasswordHash extends PasswordHash {}


[tomee] 06/17: TOMEE-2365 - Implemented SecurityContext getCallerPrincipal.

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 2ec12245f4db84371ed068b7284a0d8bebd5877f
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Tue Jan 15 23:07:56 2019 +0000

    TOMEE-2365 - Implemented SecurityContext getCallerPrincipal.
---
 tomee/tomee-security/pom.xml                       |  6 +++
 .../tomee/security/TomEESecurityContext.java       | 29 ++++++++++++++-
 .../security/http/TomEEHttpMessageContext.java     |  8 ++++
 .../security/context/SecurityContextTest.java      | 43 +++++++++++++++++++++-
 4 files changed, 83 insertions(+), 3 deletions(-)

diff --git a/tomee/tomee-security/pom.xml b/tomee/tomee-security/pom.xml
index d720e82..597e9e4 100644
--- a/tomee/tomee-security/pom.xml
+++ b/tomee/tomee-security/pom.xml
@@ -55,6 +55,12 @@
       <version>${project.version}</version>
       <scope>provided</scope>
     </dependency>
+    <dependency>
+      <groupId>org.apache.tomee</groupId>
+      <artifactId>tomee-catalina</artifactId>
+      <version>${project.version}</version>
+      <scope>provided</scope>
+    </dependency>
 
     <!-- Test -->
     <dependency>
diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/TomEESecurityContext.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/TomEESecurityContext.java
index 2e31b06..57df3f6 100644
--- a/tomee/tomee-security/src/main/java/org/apache/tomee/security/TomEESecurityContext.java
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/TomEESecurityContext.java
@@ -17,8 +17,14 @@
 package org.apache.tomee.security;
 
 import org.apache.catalina.authenticator.jaspic.CallbackHandlerImpl;
+import org.apache.catalina.connector.Request;
+import org.apache.openejb.loader.SystemInstance;
+import org.apache.openejb.spi.SecurityService;
+import org.apache.tomee.catalina.OpenEJBSecurityListener;
+import org.apache.tomee.catalina.TomcatSecurityService;
 import org.apache.tomee.security.message.TomEEMessageInfo;
 
+import javax.annotation.PostConstruct;
 import javax.security.auth.Subject;
 import javax.security.auth.message.AuthException;
 import javax.security.auth.message.AuthStatus;
@@ -40,9 +46,19 @@ import static javax.security.auth.message.AuthStatus.SEND_FAILURE;
 import static javax.security.auth.message.AuthStatus.SUCCESS;
 
 public class TomEESecurityContext implements SecurityContext {
+    private TomcatSecurityService securityService;
+
+    @PostConstruct
+    private void init() {
+        final SecurityService securityService = SystemInstance.get().getComponent(SecurityService.class);
+        if (securityService instanceof TomcatSecurityService) {
+            this.securityService = (TomcatSecurityService) securityService;
+        }
+    }
+
     @Override
     public Principal getCallerPrincipal() {
-        return null;
+        return securityService.getCallerPrincipal();
     }
 
     @Override
@@ -103,4 +119,15 @@ public class TomEESecurityContext implements SecurityContext {
 
         return serverAuthConfig.getAuthContext(null, null, null);
     }
+
+    public static void registerContainerAboutLogin(final Principal principal) {
+        final SecurityService securityService = SystemInstance.get().getComponent(SecurityService.class);
+        if (TomcatSecurityService.class.isInstance(securityService)) {
+            final TomcatSecurityService tomcatSecurityService = (TomcatSecurityService) securityService;
+            final Request request = OpenEJBSecurityListener.requests.get();
+            tomcatSecurityService.enterWebApp(request.getWrapper().getRealm(),
+                                              principal,
+                                              request.getWrapper().getRunAs());
+        }
+    }
 }
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 28d0e4a..16f3c29 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,12 @@
 package org.apache.tomee.security.http;
 
 import org.apache.catalina.authenticator.jaspic.MessageInfoImpl;
+import org.apache.catalina.connector.Request;
+import org.apache.openejb.loader.SystemInstance;
+import org.apache.openejb.spi.SecurityService;
+import org.apache.tomee.catalina.OpenEJBSecurityListener;
+import org.apache.tomee.catalina.TomcatSecurityService;
+import org.apache.tomee.security.TomEESecurityContext;
 import org.apache.tomee.security.message.TomEEMessageInfo;
 
 import javax.security.auth.Subject;
@@ -203,6 +209,8 @@ public final class TomEEHttpMessageContext implements HttpMessageContext {
         this.principal = principal;
         this.groups = groups;
 
+        TomEESecurityContext.registerContainerAboutLogin(principal);
+
         return SUCCESS;
     }
 
diff --git a/tomee/tomee-security/src/test/java/org/apache/tomee/security/context/SecurityContextTest.java b/tomee/tomee-security/src/test/java/org/apache/tomee/security/context/SecurityContextTest.java
index efb7898..fe491fb 100644
--- a/tomee/tomee-security/src/test/java/org/apache/tomee/security/context/SecurityContextTest.java
+++ b/tomee/tomee-security/src/test/java/org/apache/tomee/security/context/SecurityContextTest.java
@@ -38,6 +38,7 @@ import javax.servlet.http.HttpServletResponse;
 import javax.ws.rs.client.ClientBuilder;
 import javax.ws.rs.core.Response;
 import java.io.IOException;
+import java.security.Principal;
 
 import static javax.security.enterprise.identitystore.CredentialValidationResult.Status.VALID;
 import static org.junit.Assert.assertEquals;
@@ -45,7 +46,7 @@ import static org.junit.Assert.assertEquals;
 public class SecurityContextTest extends AbstractTomEESecurityTest {
     @Test
     public void authenticate() throws Exception {
-        final String servlet = "http://localhost:" + container.getConfiguration().getHttpPort() + "/securityContext";
+        final String servlet = getAppUrl() + "/securityContext";
         final Response response = ClientBuilder.newBuilder()
                                                .build()
                                                .target(servlet)
@@ -58,8 +59,22 @@ public class SecurityContextTest extends AbstractTomEESecurityTest {
     }
 
     @Test
+    public void callerPrincipal() throws Exception {
+        final String servlet = getAppUrl() + "/securityContextPrincipal";
+        final Response response = ClientBuilder.newBuilder()
+                                               .build()
+                                               .target(servlet)
+                                               .queryParam("username", "tomcat")
+                                               .queryParam("password", "tomcat")
+                                               .request()
+                                               .get();
+        assertEquals(200, response.getStatus());
+        assertEquals("tomcat", response.readEntity(String.class));
+    }
+
+    @Test
     public void wrongPassword() throws Exception {
-        final String servlet = "http://localhost:" + container.getConfiguration().getHttpPort() + "/securityContext";
+        final String servlet = getAppUrl() + "/securityContext";
         assertEquals(401, ClientBuilder.newBuilder().build()
                                        .target(servlet)
                                        .queryParam("username", "tomcat")
@@ -89,6 +104,30 @@ public class SecurityContextTest extends AbstractTomEESecurityTest {
         }
     }
 
+    @WebServlet(urlPatterns = "/securityContextPrincipal")
+    public static class PrincipalServlet extends HttpServlet {
+        @Inject
+        private SecurityContext securityContext;
+
+        @Override
+        protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
+                throws ServletException, IOException {
+
+            final AuthenticationParameters parameters =
+                    AuthenticationParameters.withParams()
+                                            .credential(new UsernamePasswordCredential(req.getParameter("username"),
+                                                                                       req.getParameter("password")))
+                                            .newAuthentication(true);
+
+            securityContext.authenticate(req, resp, parameters);
+
+            final Principal callerPrincipal = securityContext.getCallerPrincipal();
+
+            resp.getWriter().write(callerPrincipal.getName());
+        }
+    }
+
+
     public static class SecurityContextHttpAuthenticationMechanism implements HttpAuthenticationMechanism {
         @Inject
         private IdentityStoreHandler identityStoreHandler;


[tomee] 15/17: TOMEE-2365 - Added missing API for 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 c5d35aa7cc2a693c2289dd65699fa631f7d997a6
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Thu Jan 17 12:30:24 2019 +0000

    TOMEE-2365 - Added missing API for IdentityStore.
---
 .../identitystore/IdentityStorePermission.java     | 31 +++++++++++++
 .../identitystore/IdentityStoreWrapper.java        | 52 ++++++++++++++++++++++
 2 files changed, 83 insertions(+)

diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/IdentityStorePermission.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/IdentityStorePermission.java
new file mode 100644
index 0000000..a44fe50
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/IdentityStorePermission.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.identitystore;
+
+import java.security.BasicPermission;
+
+public class IdentityStorePermission extends BasicPermission {
+    private static final long serialVersionUID = 1254057022829640365L;
+
+    public IdentityStorePermission(String name) {
+        super(name);
+    }
+
+    public IdentityStorePermission(String name, String action) {
+        super(name, action);
+    }
+}
diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/IdentityStoreWrapper.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/IdentityStoreWrapper.java
new file mode 100644
index 0000000..113909a
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/IdentityStoreWrapper.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 javax.security.enterprise.identitystore;
+
+import javax.security.enterprise.credential.Credential;
+import java.util.Set;
+
+public class IdentityStoreWrapper implements IdentityStore {
+    private final IdentityStore identityStore;
+
+    public IdentityStoreWrapper(IdentityStore identityStore) {
+        this.identityStore = identityStore;
+    }
+
+    public IdentityStore getWrapped() {
+        return identityStore;
+    }
+
+    @Override
+    public CredentialValidationResult validate(Credential credential) {
+        return getWrapped().validate(credential);
+    }
+
+    @Override
+    public Set<String> getCallerGroups(CredentialValidationResult validationResult) {
+        return getWrapped().getCallerGroups(validationResult);
+    }
+
+    @Override
+    public int priority() {
+        return getWrapped().priority();
+    }
+
+    @Override
+    public Set<ValidationType> validationTypes() {
+        return getWrapped().validationTypes();
+    }
+}


[tomee] 11/17: TOMEE-2365 - Added API HttpAuthenticationMechanismWrapper.

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 776d9755d39431ea4eebe04506a05cccb6fdd129
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Thu Jan 17 12:28:28 2019 +0000

    TOMEE-2365 - Added API HttpAuthenticationMechanismWrapper.
---
 .../http/HttpAuthenticationMechanismWrapper.java   | 57 ++++++++++++++++++++++
 1 file changed, 57 insertions(+)

diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/HttpAuthenticationMechanismWrapper.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/HttpAuthenticationMechanismWrapper.java
new file mode 100644
index 0000000..352677b
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/HttpAuthenticationMechanismWrapper.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 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;
+
+public class HttpAuthenticationMechanismWrapper implements HttpAuthenticationMechanism {
+    private final HttpAuthenticationMechanism httpAuthenticationMechanism;
+
+    public HttpAuthenticationMechanismWrapper(final HttpAuthenticationMechanism httpAuthenticationMechanism) {
+        this.httpAuthenticationMechanism = httpAuthenticationMechanism;
+    }
+
+    public HttpAuthenticationMechanism getWrapped() {
+        return httpAuthenticationMechanism;
+    }
+
+    @Override
+    public AuthenticationStatus validateRequest(HttpServletRequest request,
+                                                HttpServletResponse response,
+                                                HttpMessageContext httpMessageContext)
+            throws AuthenticationException {
+        return getWrapped().validateRequest(request, response, httpMessageContext);
+    }
+
+    @Override
+    public AuthenticationStatus secureResponse(HttpServletRequest request,
+                                               HttpServletResponse response,
+                                               HttpMessageContext httpMessageContext)
+            throws AuthenticationException {
+        return getWrapped().secureResponse(request, response, httpMessageContext);
+    }
+
+    @Override
+    public void cleanSubject(HttpServletRequest request,
+                             HttpServletResponse response,
+                             HttpMessageContext httpMessageContext) {
+        getWrapped().cleanSubject(request, response, httpMessageContext);
+    }
+}


[tomee] 03/17: TOMEE-2365 - Fixed DefaultAuthenticationMechanism init.

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 999e38ee4275d769c286ee854d194d6d310e97d9
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Mon Jan 14 16:33:40 2019 +0000

    TOMEE-2365 - Fixed DefaultAuthenticationMechanism init.
---
 .../apache/tomee/security/cdi/DefaultAuthenticationMechanism.java   | 6 ++++--
 1 file changed, 4 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 cd18a17..0819eeb 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
@@ -16,6 +16,7 @@
  */
 package org.apache.tomee.security.cdi;
 
+import javax.annotation.PostConstruct;
 import javax.enterprise.context.ApplicationScoped;
 import javax.security.enterprise.AuthenticationException;
 import javax.security.enterprise.AuthenticationStatus;
@@ -28,8 +29,9 @@ import javax.servlet.http.HttpServletResponse;
 public class DefaultAuthenticationMechanism implements HttpAuthenticationMechanism {
     private HttpAuthenticationMechanism delegate;
 
-    public DefaultAuthenticationMechanism() {
-        this.delegate = new EmptyAuthenticationMechanism();
+    @PostConstruct
+    private void init() {
+        delegate = new EmptyAuthenticationMechanism();
     }
 
     @Override


[tomee] 14/17: TOMEE-2365 - Added API for LdapIdentityStore.

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 f0a53f74d4fb56d2542aef49b565a8e1930538ab
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Thu Jan 17 12:30:05 2019 +0000

    TOMEE-2365 - Added API for LdapIdentityStore.
---
 .../identitystore/LdapIdentityStoreDefinition.java | 85 ++++++++++++++++++++++
 1 file changed, 85 insertions(+)

diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/LdapIdentityStoreDefinition.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/LdapIdentityStoreDefinition.java
new file mode 100644
index 0000000..2a71657
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/LdapIdentityStoreDefinition.java
@@ -0,0 +1,85 @@
+/*
+ * 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.identitystore.IdentityStore.ValidationType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import static javax.security.enterprise.identitystore.IdentityStore.ValidationType.PROVIDE_GROUPS;
+import static javax.security.enterprise.identitystore.IdentityStore.ValidationType.VALIDATE;
+
+@Retention(RUNTIME)
+@Target(TYPE)
+public @interface LdapIdentityStoreDefinition {
+    enum LdapSearchScope {
+        ONE_LEVEL, SUBTREE
+    }
+
+    String url() default "";
+
+    String bindDn() default "";
+
+    String bindDnPassword() default "";
+
+    String callerBaseDn() default "";
+
+    String callerNameAttribute() default "uid";
+
+    String callerSearchBase() default "";
+
+    String callerSearchFilter() default "";
+
+    LdapSearchScope callerSearchScope() default LdapSearchScope.SUBTREE;
+
+    String callerSearchScopeExpression() default "";
+
+    String groupSearchBase() default "";
+
+    String groupSearchFilter() default "";
+
+    LdapSearchScope groupSearchScope() default LdapSearchScope.SUBTREE;
+
+    String groupSearchScopeExpression() default "";
+
+    String groupNameAttribute() default "cn";
+
+    String groupMemberAttribute() default "member";
+
+    String groupMemberOfAttribute() default "memberOf";
+
+    int readTimeout() default 0;
+
+    String readTimeoutExpression() default "";
+
+    int maxResults() default 1000;
+
+    String maxResultsExpression() default "";
+
+    int priority() default 80;
+
+    String priorityExpression() default "";
+
+    ValidationType[] useFor() default {
+            VALIDATE,
+            PROVIDE_GROUPS
+    };
+
+    String useForExpression() default "";
+}


[tomee] 02/17: TOMEE-2365 - Added SecurityContext 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 84530e6e3611c4162bd103d75cc11eef58bd3a80
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Mon Jan 14 16:33:12 2019 +0000

    TOMEE-2365 - Added SecurityContext API.
---
 .../javax/security/enterprise/SecurityContext.java | 36 ++++++++++++++++++++++
 1 file changed, 36 insertions(+)

diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/SecurityContext.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/SecurityContext.java
new file mode 100644
index 0000000..2282fcd
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/SecurityContext.java
@@ -0,0 +1,36 @@
+/*
+ * 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 javax.security.enterprise.authentication.mechanism.http.AuthenticationParameters;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.security.Principal;
+import java.util.Set;
+
+public interface SecurityContext {
+    Principal getCallerPrincipal();
+
+    <T extends Principal> Set<T> getPrincipalsByType(Class<T> pType);
+
+    boolean isCallerInRole(String role);
+
+    boolean hasAccessToWebResource(String resource, String... methods);
+
+    AuthenticationStatus authenticate(HttpServletRequest request, HttpServletResponse response,
+                                      AuthenticationParameters parameters);
+}


[tomee] 01/17: TOMEE-2365 - Fixed FormAuthenticationMechanism j_security_check resolution when added only to a 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 5cfae0d5a5d84344d888d2f1223ca77a4727168f
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Mon Jan 14 12:10:36 2019 +0000

    TOMEE-2365 - Fixed FormAuthenticationMechanism j_security_check resolution when added only to a servlet.
---
 .../TomEESecurityServletAuthenticationMechanismMapper.java   | 11 ++++++++++-
 .../security/provider/TomEESecurityServerAuthModule.java     |  4 +---
 .../apache/tomee/security/servlet/FormAuthServletTest.java   | 12 +++---------
 3 files changed, 14 insertions(+), 13 deletions(-)

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 2f2979c..f1772b6 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
@@ -25,8 +25,10 @@ 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.security.enterprise.authentication.mechanism.http.HttpMessageContext;
 import javax.servlet.ServletContext;
 import javax.servlet.ServletRegistration;
+import javax.servlet.http.HttpServletRequest;
 import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
@@ -82,7 +84,14 @@ public class TomEESecurityServletAuthenticationMechanismMapper {
         }
     }
 
-    public HttpAuthenticationMechanism getCurrentAuthenticationMechanism(final String servletName) {
+    public HttpAuthenticationMechanism getCurrentAuthenticationMechanism(final HttpMessageContext httpMessageContext) {
+        final HttpServletRequest request = httpMessageContext.getRequest();
+
+        if (request.getRequestURI().endsWith("j_security_check")) {
+            return CDI.current().select(FormAuthenticationMechanism.class).get();
+        }
+
+        final String servletName = request.getHttpServletMapping().getServletName();
         return servletAuthenticationMapper.getOrDefault(servletName, defaultAuthenticationMechanism);
     }
 }
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 e884f0e..f48f6db 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
@@ -68,13 +68,11 @@ public class TomEESecurityServerAuthModule implements ServerAuthModule {
         final HttpMessageContext httpMessageContext =
                 httpMessageContext(handler, 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);
+                   .getCurrentAuthenticationMechanism(httpMessageContext);
 
         final AuthenticationStatus authenticationStatus;
         try {
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 df81b39..c695223 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
@@ -23,7 +23,6 @@ import com.gargoylesoftware.htmlunit.html.HtmlPage;
 import org.apache.tomee.security.AbstractTomEESecurityTest;
 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;
@@ -55,14 +54,6 @@ public class FormAuthServletTest extends AbstractTomEESecurityTest {
         assertEquals("ok!", webClient.getPage(getAppUrl() + "/form").getWebResponse().getContentAsString());
     }
 
-    @ApplicationScoped
-    @FormAuthenticationMechanismDefinition(
-            loginToContinue = @LoginToContinue()
-    )
-    public static class ApplicationAuthentication {
-
-    }
-
     @WebServlet(urlPatterns = "/login")
     public static class LoginServlet extends HttpServlet {
         @Override
@@ -97,6 +88,9 @@ public class FormAuthServletTest extends AbstractTomEESecurityTest {
 
     @WebServlet(urlPatterns = "/form")
     @ServletSecurity(@HttpConstraint(rolesAllowed = "tomcat"))
+    @FormAuthenticationMechanismDefinition(
+            loginToContinue = @LoginToContinue()
+    )
     public static class TestServlet extends HttpServlet {
         @Override
         protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)


[tomee] 05/17: TOMEE-2365 - Implemented SecurityContext authenticate.

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 58292c94375f582f5d7fa89d5ef810b28bdab067
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Mon Jan 14 16:35:16 2019 +0000

    TOMEE-2365 - Implemented SecurityContext authenticate.
---
 .../tomee/security/TomEESecurityContext.java       | 106 ++++++++++++++++++
 .../tomee/security/cdi/TomEESecurityExtension.java |   3 +
 .../security/context/SecurityContextTest.java      | 121 +++++++++++++++++++++
 3 files changed, 230 insertions(+)

diff --git a/tomee/tomee-security/src/main/java/org/apache/tomee/security/TomEESecurityContext.java b/tomee/tomee-security/src/main/java/org/apache/tomee/security/TomEESecurityContext.java
new file mode 100644
index 0000000..2e31b06
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/org/apache/tomee/security/TomEESecurityContext.java
@@ -0,0 +1,106 @@
+/*
+ * 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;
+
+import org.apache.catalina.authenticator.jaspic.CallbackHandlerImpl;
+import org.apache.tomee.security.message.TomEEMessageInfo;
+
+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.AuthConfigFactory;
+import javax.security.auth.message.config.AuthConfigProvider;
+import javax.security.auth.message.config.ServerAuthConfig;
+import javax.security.auth.message.config.ServerAuthContext;
+import javax.security.enterprise.AuthenticationStatus;
+import javax.security.enterprise.SecurityContext;
+import javax.security.enterprise.authentication.mechanism.http.AuthenticationParameters;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.security.Principal;
+import java.util.Set;
+
+import static javax.security.auth.message.AuthStatus.SEND_CONTINUE;
+import static javax.security.auth.message.AuthStatus.SEND_FAILURE;
+import static javax.security.auth.message.AuthStatus.SUCCESS;
+
+public class TomEESecurityContext implements SecurityContext {
+    @Override
+    public Principal getCallerPrincipal() {
+        return null;
+    }
+
+    @Override
+    public <T extends Principal> Set<T> getPrincipalsByType(final Class<T> pType) {
+        return null;
+    }
+
+    @Override
+    public boolean isCallerInRole(final String role) {
+        return false;
+    }
+
+    @Override
+    public boolean hasAccessToWebResource(final String resource, final String... methods) {
+        return false;
+    }
+
+    @Override
+    public AuthenticationStatus authenticate(final HttpServletRequest request,
+                                             final HttpServletResponse response,
+                                             final AuthenticationParameters parameters) {
+
+        try {
+            final MessageInfo messageInfo = new TomEEMessageInfo(request, response, true, parameters);
+            final ServerAuthContext serverAuthContext = getServerAuthContext(request);
+            final AuthStatus authStatus = serverAuthContext.validateRequest(messageInfo, new Subject(), null);
+
+            return mapToAuthenticationStatus(authStatus);
+
+        } catch (final AuthException e) {
+            return AuthenticationStatus.SEND_FAILURE;
+        }
+    }
+
+    private AuthenticationStatus mapToAuthenticationStatus(final AuthStatus authStatus) {
+        if (SUCCESS.equals(authStatus)) {
+            return AuthenticationStatus.SUCCESS;
+        }
+
+        if (SEND_FAILURE.equals(authStatus)) {
+            return AuthenticationStatus.SEND_FAILURE;
+        }
+
+        if (SEND_CONTINUE.equals(authStatus)) {
+            return AuthenticationStatus.SEND_CONTINUE;
+        }
+
+        throw new IllegalArgumentException();
+    }
+
+    private ServerAuthContext getServerAuthContext(final HttpServletRequest request) throws AuthException {
+        final String appContext = request.getServletContext().getVirtualServerName() + " " + request.getContextPath();
+
+        final AuthConfigProvider authConfigProvider =
+                AuthConfigFactory.getFactory().getConfigProvider("HttpServlet", appContext, null);
+        final ServerAuthConfig serverAuthConfig =
+                authConfigProvider.getServerAuthConfig("HttpServlet", appContext, CallbackHandlerImpl.getInstance());
+
+        return serverAuthConfig.getAuthContext(null, null, null);
+    }
+}
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 9343c3e..092bcff 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,6 +16,7 @@
  */
 package org.apache.tomee.security.cdi;
 
+import org.apache.tomee.security.TomEESecurityContext;
 import org.apache.tomee.security.identitystore.TomEEDefaultIdentityStore;
 import org.apache.tomee.security.identitystore.TomEEIdentityStoreHandler;
 
@@ -55,6 +56,8 @@ public class TomEESecurityExtension implements Extension {
 
         beforeBeanDiscovery.addAnnotatedType(beanManager.createAnnotatedType(AutoApplySessionInterceptor.class));
         beforeBeanDiscovery.addAnnotatedType(beanManager.createAnnotatedType(LoginToContinueInterceptor.class));
+
+        beforeBeanDiscovery.addAnnotatedType(beanManager.createAnnotatedType(TomEESecurityContext.class));
     }
 
     void processAuthenticationMechanismDefinitions(@Observes
diff --git a/tomee/tomee-security/src/test/java/org/apache/tomee/security/context/SecurityContextTest.java b/tomee/tomee-security/src/test/java/org/apache/tomee/security/context/SecurityContextTest.java
new file mode 100644
index 0000000..efb7898
--- /dev/null
+++ b/tomee/tomee-security/src/test/java/org/apache/tomee/security/context/SecurityContextTest.java
@@ -0,0 +1,121 @@
+/*
+ * 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.context;
+
+import org.apache.tomee.security.AbstractTomEESecurityTest;
+import org.junit.Ignore;
+import org.junit.Test;
+
+import javax.inject.Inject;
+import javax.security.enterprise.AuthenticationException;
+import javax.security.enterprise.AuthenticationStatus;
+import javax.security.enterprise.SecurityContext;
+import javax.security.enterprise.authentication.mechanism.http.AuthenticationParameters;
+import javax.security.enterprise.authentication.mechanism.http.HttpAuthenticationMechanism;
+import javax.security.enterprise.authentication.mechanism.http.HttpMessageContext;
+import javax.security.enterprise.credential.UsernamePasswordCredential;
+import javax.security.enterprise.identitystore.CredentialValidationResult;
+import javax.security.enterprise.identitystore.IdentityStoreHandler;
+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.ClientBuilder;
+import javax.ws.rs.core.Response;
+import java.io.IOException;
+
+import static javax.security.enterprise.identitystore.CredentialValidationResult.Status.VALID;
+import static org.junit.Assert.assertEquals;
+
+public class SecurityContextTest extends AbstractTomEESecurityTest {
+    @Test
+    public void authenticate() throws Exception {
+        final String servlet = "http://localhost:" + container.getConfiguration().getHttpPort() + "/securityContext";
+        final Response response = ClientBuilder.newBuilder()
+                                               .build()
+                                               .target(servlet)
+                                               .queryParam("username", "tomcat")
+                                               .queryParam("password", "tomcat")
+                                               .request()
+                                               .get();
+        assertEquals(200, response.getStatus());
+        assertEquals("ok!", response.readEntity(String.class));
+    }
+
+    @Test
+    public void wrongPassword() throws Exception {
+        final String servlet = "http://localhost:" + container.getConfiguration().getHttpPort() + "/securityContext";
+        assertEquals(401, ClientBuilder.newBuilder().build()
+                                       .target(servlet)
+                                       .queryParam("username", "tomcat")
+                                       .queryParam("password", "wrong")
+                                       .request()
+                                       .get().getStatus());
+    }
+
+    @WebServlet(urlPatterns = "/securityContext")
+    public static class TestServlet extends HttpServlet {
+        @Inject
+        private SecurityContext securityContext;
+
+        @Override
+        protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
+                throws ServletException, IOException {
+
+            final AuthenticationParameters parameters =
+                    AuthenticationParameters.withParams()
+                                            .credential(new UsernamePasswordCredential(req.getParameter("username"),
+                                                                                       req.getParameter("password")))
+                                            .newAuthentication(true);
+
+            securityContext.authenticate(req, resp, parameters);
+
+            resp.getWriter().write("ok!");
+        }
+    }
+
+    public static class SecurityContextHttpAuthenticationMechanism implements HttpAuthenticationMechanism {
+        @Inject
+        private IdentityStoreHandler identityStoreHandler;
+
+        @Override
+        public AuthenticationStatus validateRequest(final HttpServletRequest request,
+                                                    final HttpServletResponse response,
+                                                    final HttpMessageContext httpMessageContext)
+                throws AuthenticationException {
+
+            if (httpMessageContext.isAuthenticationRequest()) {
+                try {
+                    final CredentialValidationResult result =
+                            identityStoreHandler.validate(httpMessageContext.getAuthParameters().getCredential());
+
+                    if (result.getStatus().equals(VALID)) {
+                        return httpMessageContext.notifyContainerAboutLogin(result);
+                    }
+
+                } catch (final IllegalArgumentException | IllegalStateException e) {
+                    // Something was sent in the header was not valid.
+                }
+
+                return httpMessageContext.responseUnauthorized();
+            }
+
+            return httpMessageContext.doNothing();
+        }
+    }
+}


[tomee] 17/17: TOMEE-2365 - Checkstyle issues.

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 0373733fcd6c7c41a7dc2afbc44bf745eccfb1d5
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Thu Jan 17 12:58:26 2019 +0000

    TOMEE-2365 - Checkstyle issues.
---
 .../enterprise/authentication/mechanism/http/AutoApplySession.java     | 3 +--
 .../apache/tomee/security/provider/TomEESecurityServerAuthModule.java  | 1 -
 2 files changed, 1 insertion(+), 3 deletions(-)

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
index 534e78f..291c726 100644
--- 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
@@ -31,10 +31,9 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
 @Target(TYPE)
 public @interface AutoApplySession {
     @SuppressWarnings("all")
-    public final static class Literal extends AnnotationLiteral<AutoApplySession> implements AutoApplySession {
+    public static final class Literal extends AnnotationLiteral<AutoApplySession> implements AutoApplySession {
         private static final long serialVersionUID = 1L;
 
         public static final Literal INSTANCE = new Literal();
-
     }
 }
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 f48f6db..ad505c0 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
@@ -30,7 +30,6 @@ 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;


[tomee] 08/17: TOMEE-2365 - Added RememberMe 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 0215b142ebb44e525f3b93e6ce7129b6314232be
Author: Roberto Cortez <ra...@yahoo.com>
AuthorDate: Wed Jan 16 16:48:39 2019 +0000

    TOMEE-2365 - Added RememberMe API.
---
 .../authentication/mechanism/http/RememberMe.java  | 215 +++++++++++++++++++++
 .../credential/RememberMeCredential.java           |  29 +++
 .../identitystore/RememberMeIdentityStore.java     |  29 +++
 3 files changed, 273 insertions(+)

diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/RememberMe.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/RememberMe.java
new file mode 100644
index 0000000..e8b7e47
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/authentication/mechanism/http/RememberMe.java
@@ -0,0 +1,215 @@
+/*
+ * 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.AnnotationLiteral;
+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 RememberMe {
+    @Nonbinding
+    int cookieMaxAgeSeconds() default 86400;
+
+    @Nonbinding
+    String cookieMaxAgeSecondsExpression() default "";
+
+    @Nonbinding
+    boolean cookieSecureOnly() default true;
+
+    @Nonbinding
+    String cookieSecureOnlyExpression() default "";
+
+    @Nonbinding
+    boolean cookieHttpOnly() default true;
+
+    @Nonbinding
+    String cookieHttpOnlyExpression() default "";
+
+    @Nonbinding
+    String cookieName() default "JREMEMBERMEID";
+
+    @Nonbinding
+    boolean isRememberMe() default true;
+
+    @Nonbinding
+    String isRememberMeExpression() default "";
+
+    final class Literal extends AnnotationLiteral<RememberMe> implements RememberMe {
+        private static final long serialVersionUID = 1L;
+
+        private final int cookieMaxAgeSeconds;
+        private final String cookieMaxAgeSecondsExpression;
+        private final boolean cookieSecureOnly;
+        private final String cookieSecureOnlyExpression;
+        private final boolean cookieHttpOnly;
+        private final String cookieHttpOnlyExpression;
+        private final String cookieName;
+        private final boolean isRememberMe;
+        private final String isRememberMeExpression;
+
+        public static LiteralBuilder builder() {
+            return new LiteralBuilder();
+        }
+
+        public static class LiteralBuilder {
+            private int cookieMaxAgeSeconds = 86400;
+            private String cookieMaxAgeSecondsExpression;
+            private boolean cookieSecureOnly = true;
+            private String cookieSecureOnlyExpression;
+            private boolean cookieHttpOnly = true;
+            private String cookieHttpOnlyExpression;
+            private String cookieName = "JREMEMBERMEID";
+            private boolean isRememberMe = true;
+            private String isRememberMeExpression;
+
+            public LiteralBuilder cookieMaxAgeSeconds(int cookieMaxAgeSeconds) {
+                this.cookieMaxAgeSeconds = cookieMaxAgeSeconds;
+                return this;
+            }
+
+            public LiteralBuilder cookieMaxAgeSecondsExpression(String cookieMaxAgeSecondsExpression) {
+                this.cookieMaxAgeSecondsExpression = cookieMaxAgeSecondsExpression;
+                return this;
+            }
+
+            public LiteralBuilder cookieSecureOnly(boolean cookieSecureOnly) {
+                this.cookieSecureOnly = cookieSecureOnly;
+                return this;
+
+            }
+
+            public LiteralBuilder cookieSecureOnlyExpression(String cookieSecureOnlyExpression) {
+                this.cookieSecureOnlyExpression = cookieSecureOnlyExpression;
+                return this;
+            }
+
+            public LiteralBuilder cookieHttpOnly(boolean cookieHttpOnly) {
+                this.cookieHttpOnly = cookieHttpOnly;
+                return this;
+            }
+
+            public LiteralBuilder cookieHttpOnlyExpression(String cookieHttpOnlyExpression) {
+                this.cookieHttpOnlyExpression = cookieHttpOnlyExpression;
+                return this;
+            }
+
+            public LiteralBuilder cookieName(String cookieName) {
+                this.cookieName = cookieName;
+                return this;
+            }
+
+            public LiteralBuilder isRememberMe(boolean isRememberMe) {
+                this.isRememberMe = isRememberMe;
+                return this;
+            }
+
+            public LiteralBuilder isRememberMeExpression(String isRememberMeExpression) {
+                this.isRememberMeExpression = isRememberMeExpression;
+                return this;
+            }
+
+            public Literal build() {
+                return new Literal(
+                        cookieMaxAgeSeconds,
+                        cookieMaxAgeSecondsExpression,
+                        cookieSecureOnly,
+                        cookieSecureOnlyExpression,
+                        cookieHttpOnly,
+                        cookieHttpOnlyExpression,
+                        cookieName,
+                        isRememberMe,
+                        isRememberMeExpression);
+            }
+        }
+
+        public Literal(int cookieMaxAgeSeconds,
+                       String cookieMaxAgeSecondsExpression,
+                       boolean cookieSecureOnly,
+                       String cookieSecureOnlyExpression,
+                       boolean cookieHttpOnly,
+                       String cookieHttpOnlyExpression,
+                       String cookieName,
+                       boolean isRememberMe,
+                       String isRememberMeExpression) {
+
+            this.cookieMaxAgeSeconds = cookieMaxAgeSeconds;
+            this.cookieMaxAgeSecondsExpression = cookieMaxAgeSecondsExpression;
+            this.cookieSecureOnly = cookieSecureOnly;
+            this.cookieSecureOnlyExpression = cookieSecureOnlyExpression;
+            this.cookieHttpOnly = cookieHttpOnly;
+            this.cookieHttpOnlyExpression = cookieHttpOnlyExpression;
+            this.cookieName = cookieName;
+            this.isRememberMe = isRememberMe;
+            this.isRememberMeExpression = isRememberMeExpression;
+        }
+
+        @Override
+        public boolean cookieHttpOnly() {
+            return cookieHttpOnly;
+        }
+
+        @Override
+        public String cookieHttpOnlyExpression() {
+            return cookieHttpOnlyExpression;
+        }
+
+        @Override
+        public int cookieMaxAgeSeconds() {
+            return cookieMaxAgeSeconds;
+        }
+
+        @Override
+        public String cookieMaxAgeSecondsExpression() {
+            return cookieMaxAgeSecondsExpression;
+        }
+
+        @Override
+        public boolean cookieSecureOnly() {
+            return cookieSecureOnly;
+        }
+
+        @Override
+        public String cookieSecureOnlyExpression() {
+            return cookieSecureOnlyExpression;
+        }
+
+        @Override
+        public String cookieName() {
+            return cookieName;
+        }
+
+        @Override
+        public boolean isRememberMe() {
+            return isRememberMe;
+        }
+
+        @Override
+        public String isRememberMeExpression() {
+            return isRememberMeExpression;
+        }
+    }
+}
diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/credential/RememberMeCredential.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/credential/RememberMeCredential.java
new file mode 100644
index 0000000..91bdcb0
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/credential/RememberMeCredential.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 class RememberMeCredential implements Credential {
+    private final String token;
+
+    public RememberMeCredential(String token) {
+        this.token = token;
+    }
+
+    public String getToken() {
+        return token;
+    }
+}
diff --git a/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/RememberMeIdentityStore.java b/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/RememberMeIdentityStore.java
new file mode 100644
index 0000000..257ebe7
--- /dev/null
+++ b/tomee/tomee-security/src/main/java/javax/security/enterprise/identitystore/RememberMeIdentityStore.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.identitystore;
+
+import javax.security.enterprise.CallerPrincipal;
+import javax.security.enterprise.credential.RememberMeCredential;
+import java.util.Set;
+
+public interface RememberMeIdentityStore {
+    CredentialValidationResult validate(RememberMeCredential credential);
+
+    String generateLoginToken(CallerPrincipal callerPrincipal, Set<String> groups);
+
+    void removeLoginToken(String token);
+}