package de.novatec.bpm.webapp.impl.security.auth;

import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.security.auth.Subject;

import org.camunda.bpm.webapp.impl.security.auth.Authentications;

/**
 * This Servlet filter relies on the Servlet container (application server) to
 * authenticate a user and only forward a request to the application upon
 * successful authentication.
 *
 * In addition this variation expects the container to also look up the groups.
 *
 * The filter passes the username and groups provided by the container through
 * the Servlet API into the Servlet session used by the Camunda REST API.
 *
 * @author Falko Menge
 */
public class ContainerBasedUserAndGroupsAuthenticationFilter extends ContainerBasedUserAuthenticationFilter {

  @Override
  protected void doLogin(Authentications authentications, String username, String engineName) {
    // get user's groups
    AccessControlContext acc = AccessController.getContext();
    Subject subject = Subject.getSubject(acc);
    Set<Principal> groupPrincipals = subject.getPrincipals();
    // transform into array of strings:
    List<String> groupIds = new ArrayList<String>();
    for (Principal groupPrincipal : groupPrincipals) {
      groupIds.add(groupPrincipal.getName());
    }

    new ContainerBasedUserAuthenticationResource().doLogin(engineName, username, authentications, groupIds);
  }

}

@@ -1007,24 +1007,161 @@
 gineName) %7B%0A
+    // initialize with null, to allow fall back to identity service, if nothing provided by container%0A    List%3CString%3E groupIds = null;%0A%0A
     // get u
@@ -1282,16 +1282,45 @@
 t(acc);%0A
+    if (subject != null) %7B%0A  
     Set%3C
@@ -1369,24 +1369,95 @@
 incipals();%0A
+      if (groupPrincipals != null && !groupPrincipals.isEmpty()) %7B%0A    
     // trans
@@ -1484,36 +1484,27 @@
 trings:%0A    
-List%3CString%3E
+   
  groupIds = 
@@ -1532,16 +1532,20 @@
 ();%0A    
+ 
+   
 for (Pri
@@ -1589,24 +1589,28 @@
 ls) %7B%0A      
+    
 groupIds.add
@@ -1637,16 +1637,34 @@
 ame());%0A
+        %7D%0A      %7D%0A
     %7D%0A%0A 

fix NPE and fall back to Identity Service