Call a secured EJB method on servlet on load(EAP 6.4) - security

I am trying to call a secured EJB method on server load but I am getting exception:
09:49:58,011 ERROR [org.jboss.as.ejb3.invocation] (ServerService Thread Pool -- 54) JBAS014134: EJB Invocation failed on component SecuredEJB for method public java.lang.String org.jboss.as.quickstarts.ejb_security.SecuredEJB.getSecurityInfo(): javax.ejb.EJBAccessException: JBAS014502: Invocation on method: public java.lang.String org.jboss.as.quickstarts.ejb_security.SecuredEJB.getSecurityInfo() of bean: SecuredEJB is not allowed
at org.jboss.as.ejb3.security.AuthorizationInterceptor.processInvocation(AuthorizationInterceptor.java:114) [jboss-as-ejb3-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.2.Final-redhat-1.jar:1.1.2.Final-redhat-1]
at org.jboss.as.ejb3.security.SecurityContextInterceptor.processInvocation(SecurityContextInterceptor.java:86) [jboss-as-ejb3-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.2.Final-redhat-1.jar:1.1.2.Final-redhat-1]
at org.jboss.as.ejb3.component.interceptors.ShutDownInterceptorFactory$1.processInvocation(ShutDownInterceptorFactory.java:64) [jboss-as-ejb3-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.2.Final-redhat-1.jar:1.1.2.Final-redhat-1]
at org.jboss.as.ejb3.component.interceptors.LoggingInterceptor.processInvocation(LoggingInterceptor.java:59) [jboss-as-ejb3-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.2.Final-redhat-1.jar:1.1.2.Final-redhat-1]
at org.jboss.as.ee.component.NamespaceContextInterceptor.processInvocation(NamespaceContextInterceptor.java:50) [jboss-as-ee-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.2.Final-redhat-1.jar:1.1.2.Final-redhat-1]
at org.jboss.as.ejb3.component.interceptors.AdditionalSetupInterceptor.processInvocation(AdditionalSetupInterceptor.java:55) [jboss-as-ejb3-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.2.Final-redhat-1.jar:1.1.2.Final-redhat-1]
at org.jboss.as.ee.component.TCCLInterceptor.processInvocation(TCCLInterceptor.java:45) [jboss-as-ee-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.2.Final-redhat-1.jar:1.1.2.Final-redhat-1]
at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61) [jboss-invocation-1.1.2.Final-redhat-1.jar:1.1.2.Final-redhat-1]
at org.jboss.as.ee.component.ViewService$View.invoke(ViewService.java:185) [jboss-as-ee-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
at org.jboss.as.ee.component.ViewDescription$1.processInvocation(ViewDescription.java:185) [jboss-as-ee-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.2.Final-redhat-1.jar:1.1.2.Final-redhat-1]
at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61) [jboss-invocation-1.1.2.Final-redhat-1.jar:1.1.2.Final-redhat-1]
at org.jboss.as.ee.component.ProxyInvocationHandler.invoke(ProxyInvocationHandler.java:73) [jboss-as-ee-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
at org.jboss.as.quickstarts.ejb_security.SecuredEJB$$$view1.getSecurityInfo(Unknown Source) [classes:]
at org.jboss.as.quickstarts.ejb_security.SecuredEJBServlet.init(SecuredEJBServlet.java:55) [classes:]
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1194) [jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1]
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1100) [jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1]
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:3593) [jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1]
at org.apache.catalina.core.StandardContext.start(StandardContext.java:3802) [jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1]
at org.jboss.as.web.deployment.WebDeploymentService.doStart(WebDeploymentService.java:163) [jboss-as-web-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
at org.jboss.as.web.deployment.WebDeploymentService.access$000(WebDeploymentService.java:61) [jboss-as-web-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
at org.jboss.as.web.deployment.WebDeploymentService$1.run(WebDeploymentService.java:96) [jboss-as-web-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) [rt.jar:1.7.0_55]
at java.util.concurrent.FutureTask.run(FutureTask.java:262) [rt.jar:1.7.0_55]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_55]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_55]
at java.lang.Thread.run(Thread.java:745) [rt.jar:1.7.0_55]
at org.jboss.threads.JBossThread.run(JBossThread.java:122) [jboss-threads-2.1.2.Final-redhat-1.jar:2.1.2.Final-redhat-1]
My project structure is:
SecuredEJBServlet.java
#SuppressWarnings("serial")
#WebServlet("/SecuredEJBServlet")
#ServletSecurity(#HttpConstraint(rolesAllowed = "quickstarts"))
public class SecuredEJBServlet extends HttpServlet {
#EJB
private SecuredEJB securedEJB;
#Override
public void init(javax.servlet.ServletConfig arg0) throws javax.servlet.ServletException{
Subject s = CMnJAASLogin.loginMethod();
runAs(s);
super.init(arg0);
System.out.println("Inside init...");
securedEJB.getName();
//securedEJB.getSecurityInfo();
}
private void runAs(Subject s){
Subject.doAs(s, new PrivilegedAction<Object>() {
#Override
public Object run() {
System.out.println("Inside privileged action");
securedEJB.getSecurityInfo();
return null;
}
});
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
securedEJB.getName();
String principal = securedEJB.getSecurityInfo();
...
}
SecuredEJB.java
#Stateless
#DeclareRoles("java")
#SecurityDomain("custom")
public class SecuredEJB {
#Resource
private SessionContext ctx;
#RolesAllowed({ "java" })
public String getSecurityInfo() {
Principal principal = ctx.getCallerPrincipal();
return principal.toString();
}
#PermitAll
public void getName(){
System.out.println(principal.getName());
}
}
CMnAuthenticator.java
public class CMnAuthenticator extends UsernamePasswordLoginModule{
#Override
protected String getUsersPassword() throws LoginException {
return "java";
}
#Override
protected boolean validatePassword(String passwordWant, String passwordHave){
return true;
}
#Override
protected Group[] getRoleSets() throws LoginException {
HashMap setsMap = new HashMap();
String groupName = "Roles";
Group group = (Group) setsMap.get(groupName);
if (group == null) {
group = new SimpleGroup(groupName);
setsMap.put(groupName, group);
}
try {
Principal p = super.createIdentity("quickstarts");
group.addMember(p);
}
catch (Exception e) {
e.printStackTrace();
}
Group[] roleSets = new Group[setsMap.size()];
setsMap.values().toArray(roleSets);
return roleSets;
}
}
CMnEJBAuthenticator.java
public class CMnEJBAuthenticator extends UsernamePasswordLoginModule {
#Override
protected String getUsersPassword() throws LoginException {
return "java";
}
#Override
protected boolean validatePassword(String passwordWant, String passwordHave){
return true;
}
#Override
protected Group[] getRoleSets() throws LoginException {
System.out.println("Inside CMnEJBAuthenticator:getRoleSets...");
HashMap setsMap = new HashMap();
String groupName = "Roles";
Group group = (Group) setsMap.get(groupName);
if (group == null) {
group = new SimpleGroup(groupName);
setsMap.put(groupName, group);
}
try {
Principal p = super.createIdentity("java");
group.addMember(p);
}
catch (Exception e) {
e.printStackTrace();
}
Group[] roleSets = new Group[setsMap.size()];
setsMap.values().toArray(roleSets);
return roleSets;
}
}
jboss-web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE jboss-web>
<jboss-web xmlns="http://www.jboss.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.jboss.org/schema/jbossas
http://www.jboss.org/schema/jbossas/jboss-web_7_2.xsd">
<!-- Configure usage of the security domain "other" -->
<security-domain>servlet-security-quickstart</security-domain>
<disable-audit>true</disable-audit>
</jboss-web>
web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<!-- Configure login to be HTTP Basic -->
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>RealmUsersRoles</realm-name>
</login-config>
<servlet>
<servlet-name>bootstrap</servlet-name>
<servlet-class>org.jboss.as.quickstarts.ejb_security.SecuredEJBServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>bootstrap</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
standalone.xml
<security-domain name="custom" cache-type="default">
<authentication>
<login-module code="org.jboss.as.quickstarts.ejb_security.others.CMnEJBAuthenticator" flag="required">
<module-option name="unauthenticatedIdentity" value="Super"/>
</login-module>
</authentication>
</security-domain>
<security-domain name="servlet-security-quickstart" cache-type="default">
<authentication>
<login-module code="org.jboss.as.quickstarts.ejb_security.others.CMnAuthenticator" flag="required">
<module-option name="unauthenticatedIdentity" value="Super"/>
</login-module>
</authentication>
</security-domain>
Jaas Authentication:
package org.jboss.as.quickstarts.ejb_security.others;
import javax.security.auth.Subject;
import javax.security.auth.callback.*;
import javax.security.auth.login.LoginContext;
import java.io.IOException;
public class CMnJAASLogin {
public static Subject loginMethod(){
LoginContext lc = null;
CallbackHandler cabHndlr = new CallbackHandler() {
#Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (int i = 0; i < callbacks.length; i++) {
if (callbacks[i] instanceof NameCallback) {
NameCallback nc = (NameCallback) callbacks[i];
nc.setName("java");
} else if (callbacks[i] instanceof PasswordCallback) {
PasswordCallback pc = (PasswordCallback) callbacks[i];
pc.setPassword("java".toCharArray());
} else {
throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
}
}
}
};
try {
lc = new LoginContext("custom", cabHndlr);
lc.login();
return lc.getSubject();
}catch(Exception ex){
ex.printStackTrace();
}
return null;
}
}
Any idea what I am missing?
Note: I am working on JBoss EAP 6.4 and java 1.7
Adding #RunAs("java") to Servlet class solves this immediate problem.
But in case, i need to deny access for other users, RunAs annotation won't help there.
So, I am required to solve it in this way(if no user is calling the method/ejb/servlet, use "java" else use that users' role.

I have not tried this, but §15.3.1 of the servlet spec says that you just need to add a run-as element to your servlet definition in the web.xml:
<servlet>
<servlet-name>bootstrap</servlet-name>
<servlet-class>org.jboss.as.quickstarts.ejb_security.SecuredEJBServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<run-as>java</run-as>
</servlet>
However, it is not completely clear whether or not the actual authenticated principal will be propagated to the EJBs for the normally authenticated servlet calls. You will have to try it and see.

I solved it after using org.jboss.security.ClientLoginModule in AppConfigurationProperty.
Finally, JAAS class looks like this:
import javax.security.auth.Subject;
import javax.security.auth.callback.*;
import javax.security.auth.login.AppConfigurationEntry;
import javax.security.auth.login.Configuration;
import javax.security.auth.login.LoginContext;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class CMnJAASLogin {
public static LoginContext loginMethod() {
LoginContext lc = null;
CallbackHandler cabHndlr = new CallbackHandler() {
#Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (int i = 0; i < callbacks.length; i++) {
if (callbacks[i] instanceof NameCallback) {
NameCallback nc = (NameCallback) callbacks[i];
nc.setName("java");
} else if (callbacks[i] instanceof PasswordCallback) {
PasswordCallback pc = (PasswordCallback) callbacks[i];
pc.setPassword("java".toCharArray());
} else {
throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
}
}
}
};
try {
String configurationName = "JBoss Test";
Configuration config = new JBossJaasConfiguration(configurationName);
lc = new LoginContext(configurationName, new Subject(), cabHndlr, config);
return lc;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
static class JBossJaasConfiguration extends Configuration {
private final String configurationName;
JBossJaasConfiguration(String configurationName) {
this.configurationName = configurationName;
}
#Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
if (!configurationName.equals(name)) {
throw new IllegalArgumentException("Unexpected configuration name '" + name + "'");
}
return new AppConfigurationEntry[]{
createClientLoginModuleConfigEntry(),
};
}
private AppConfigurationEntry createClientLoginModuleConfigEntry() {
Map<String, String> options = new HashMap<String, String>();
options.put("multi-threaded", "true");
options.put("restore-login-identity", "true");
return new AppConfigurationEntry("org.jboss.security.ClientLoginModule",
AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
}
}
}
Whole project is uploaded to: https://github.com/shekharswaraj/EJBSecurity
NOTE: It is just a test project with many hard coded values. The whole project has been modified on top of ejb-security project from EAP6.4 quickstart.

Related

Bug with omnifaces 1.10 when OmniPartialViewContext#startDocument performs transparent redirection

I am using the following stack :
PrimeFaces 5.3.1
MyFaces 2.2.8
OpenWebBeans 1.6.2
OmniFaces 1.10
DeltaSpike 1.5.1
Tomcat 8.0.28
AFAI understand, only MyFaces and OmniFaces are important there.
I have a bug when an ajax request is performed by a client whose session is expired and when the access to the page is controlled by a <security-constraint> in the webapp web.xml.
In that case, OmniPartialViewContext#startDocument perform a "transparent redirect", to provide a better explanation (see https://github.com/omnifaces/omnifaces/blob/master/src/main/java/org/omnifaces/context/OmniPartialViewContext.java#L275 ) (this function is unchanged from version 1.10 to current 1.11).
#Override
public void startDocument() throws IOException {
wrapped.startDocument();
String loginURL = WebXml.INSTANCE.getFormLoginPage();
if (loginURL != null) {
FacesContext facesContext = FacesContext.getCurrentInstance();
String loginViewId = normalizeViewId(facesContext, loginURL);
if (loginViewId.equals(getViewId(facesContext))) {
String originalURL = getRequestAttribute(facesContext, "javax.servlet.forward.request_uri");
if (originalURL != null) {
redirect(originalURL);
}
}
}
}
This is a problem because, higher in the stack, org.apache.myfaces.context.servlet.PartialViewContextImpl.processPartialRendering does lines 466 and following :
{
String currentEncoding = writer.getCharacterEncoding();
writer.writePreamble("<?xml version=\"1.0\" encoding=\""+
(currentEncoding == null ? "UTF-8" : currentEncoding) +"\"?>");
writer.startDocument();
writer.writeAttribute("id", viewRoot.getContainerClientId(_facesContext),"id");
So, an exception like the following is raised when trying to write the id, because no element is currently opened.
16-Nov-2015 16:36:35.980 SEVERE [http-apr-8444-exec-10] org.omnifaces.exceptionhandler.FullAjaxExceptionHandler.logException FullAjaxExceptionHandler: An exception occurred during rendering JSF ajax response. Error page '/error.xhtml' will be shown.
java.lang.IllegalStateException: Must be called before the start element is closed (attribute 'id')
at org.apache.myfaces.shared.renderkit.html.HtmlResponseWriterImpl.writeAttribute(HtmlResponseWriterImpl.java:816)
at javax.faces.context.ResponseWriterWrapper.writeAttribute(ResponseWriterWrapper.java:109)
at org.apache.myfaces.context.PartialResponseWriterImpl.writeAttribute(PartialResponseWriterImpl.java:407)
at javax.faces.context.ResponseWriterWrapper.writeAttribute(ResponseWriterWrapper.java:109)
at javax.faces.context.ResponseWriterWrapper.writeAttribute(ResponseWriterWrapper.java:109)
at org.apache.myfaces.context.servlet.PartialViewContextImpl.processPartialRendering(PartialViewContextImpl.java:473)
at org.apache.myfaces.context.servlet.PartialViewContextImpl.processPartial(PartialViewContextImpl.java:415)
at org.primefaces.context.PrimePartialViewContext.processPartial(PrimePartialViewContext.java:60)
at javax.faces.context.PartialViewContextWrapper.processPartial(PartialViewContextWrapper.java:85)
at javax.faces.component.UIViewRoot.encodeChildren(UIViewRoot.java:516)
at javax.faces.component.UIComponentBase.encodeAll(UIComponentBase.java:541)
at org.apache.myfaces.view.facelets.FaceletViewDeclarationLanguage.renderView(FaceletViewDeclarationLanguage.java:1891)
at org.apache.myfaces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:313)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:58)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:58)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:58)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:58)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:58)
at org.apache.myfaces.lifecycle.RenderResponseExecutor.execute(RenderResponseExecutor.java:116)
at org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:267)
at org.apache.deltaspike.jsf.impl.listener.request.DeltaSpikeLifecycleWrapper.render(DeltaSpikeLifecycleWrapper.java:111)
at javax.faces.lifecycle.LifecycleWrapper.render(LifecycleWrapper.java:31)
at org.apache.deltaspike.jsf.impl.listener.request.JsfClientWindowAwareLifecycleWrapper.render(JsfClientWindowAwareLifecycleWrapper.java:160)
at org.apache.deltaspike.jsf.impl.listener.request.DeltaSpikeLifecycleWrapper.render(DeltaSpikeLifecycleWrapper.java:111)
at javax.faces.lifecycle.LifecycleWrapper.render(LifecycleWrapper.java:31)
at org.apache.deltaspike.jsf.impl.listener.request.JsfClientWindowAwareLifecycleWrapper.render(JsfClientWindowAwareLifecycleWrapper.java:160)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:200)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.logging.log4j.web.Log4jServletFilter.doFilter(Log4jServletFilter.java:71)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:720)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:466)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:391)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318)
at org.apache.catalina.authenticator.FormAuthenticator.forwardToLoginPage(FormAuthenticator.java:384)
at org.apache.catalina.authenticator.FormAuthenticator.authenticate(FormAuthenticator.java:229)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:577)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.authenticator.SingleSignOn.invoke(SingleSignOn.java:291)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2503)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2492)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
How can I correct that (appart from dropping OmniFaces, which is really cool, and that I would really like to keep. :-) ) ?
Eventually, I am using the following solution, which can be seen as a work around, as patching MyFaces or OmniFaces is out of my reach...
I am adding my own PartialViewContext at the top of the processing chain. This way, I can perform a clean redirect on an ajax request when I can see it is trying to get the login page.
To do so, one has to :
implement a PartialViewContextFactory
implement a PartialViewContext
declare the PartialViewContextFactory in the faces-config.xml file
So, in my webapp faces-config.xml, I put :
<factory>
<partial-view-context-factory>fr.senat.context.SenatPartialViewContextFactory</partial-view-context-factory>
</factory>
My PartialViewContextFactory is dead simple :
package fr.senat.context;
import javax.faces.context.FacesContext;
import javax.faces.context.PartialViewContext;
import javax.faces.context.PartialViewContextFactory;
import lombok.Getter;
/**
*
* #author lpenet
*/
public class SenatPartialViewContextFactory extends PartialViewContextFactory {
#Getter
private final PartialViewContextFactory wrapped;
public SenatPartialViewContextFactory(PartialViewContextFactory wrapped) {
this.wrapped = wrapped;
}
#Override
public PartialViewContext getPartialViewContext(FacesContext context) {
return new SenatPartialViewContext(wrapped.getPartialViewContext(context));
}
}
and the PartialViewContext is quite simple too :
package fr.senat.context;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.context.PartialResponseWriter;
import javax.faces.context.PartialViewContext;
import javax.faces.context.PartialViewContextWrapper;
import javax.faces.event.PhaseId;
import javax.servlet.http.HttpServletRequest;
import lombok.Getter;
import org.apache.myfaces.context.servlet.PartialViewContextImpl;
import org.omnifaces.config.WebXml;
import static org.omnifaces.util.FacesLocal.getRequestAttribute;
import static org.omnifaces.util.FacesLocal.getViewId;
import static org.omnifaces.util.FacesLocal.normalizeViewId;
/**
*
* #author lpenet
*/
public class SenatPartialViewContext extends PartialViewContextWrapper {
#Getter
private final PartialViewContext wrapped;
public SenatPartialViewContext(PartialViewContext wrapped) {
this.wrapped = wrapped;
}
private void processPartialRendering() throws IOException
{
FacesContext facesContext = FacesContext.getCurrentInstance();
UIViewRoot viewRoot = facesContext.getViewRoot();
String loginURL = WebXml.INSTANCE.getFormLoginPage();
if (loginURL != null) {
String loginViewId = normalizeViewId(facesContext, loginURL);
if (loginViewId.equals(getViewId(facesContext))) {
String originalURL = getRequestAttribute(facesContext, "javax.servlet.forward.request_uri");
if (originalURL != null) {
PartialResponseWriter writer = facesContext.getPartialViewContext().getPartialResponseWriter();
writer.startDocument();
HttpServletRequest request = (HttpServletRequest) facesContext.getExternalContext().getRequest();
writer.redirect(request.getContextPath() + loginURL);
writer.endDocument();
return;
}
}
}
wrapped.processPartial(PhaseId.RENDER_RESPONSE);
}
#Override
public void processPartial(PhaseId phaseId)
{
if (phaseId == PhaseId.RENDER_RESPONSE)
{
try {
processPartialRendering();
}
catch (IOException ex)
{
Logger log = Logger.getLogger(PartialViewContextImpl.class.getName());
if (log.isLoggable(Level.SEVERE))
{
log.log(Level.SEVERE, "", ex);
}
}
} else {
wrapped.processPartial(phaseId);
}
}
}

jsf reusuble component jar gives expression error

I am studying on developing JSF 2.2 component jar library. I have developed a simple MyDataTablecomponent for this purpose.
MyDataTableLib.jar contains 3 packages:
1) META-INF which contains following MyDataTableTag.taglib.xml file
<?xml version="1.0" encoding="UTF-8"?>
<facelet-taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd">
<namespace>http:java.sun.com/MyDataTableTag</namespace>
<tag>
<tag-name>MyDataTableTag</tag-name>
<component>
<component-type>com.components.MyDataTable</component-type>
<renderer-type>com.renderer.MyRenderer</renderer-type>
</component>
<attribute>
<name>title</name>
<rtexprvalue>true</rtexprvalue>
<type>java.lang.String</type>
</attribute>
<attribute>
<name>binding</name>
<required>true</required>
<deferred-value>com.components.MyDataTable</deferred-value>
</attribute>
</tag>
</facelet-taglib>
2)com.componentswhich contains following MyDataTablecomponent
package com.components;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import javax.faces.component.FacesComponent;
import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;
#FacesComponent(value = MyDataTable.MY_TYPE)
public class MyDataTable extends UIComponentBase {
public static final String MY_FAMILY = "com.components.MyDataTable";
public static final String MY_TYPE = "com.components.MyDataTable";
public static final String MY_RENDERER_TYPE = "com.renderer.MyRenderer";
String Title, columnnames[], data[][];
DataBaseManagement db;
#Override
public String getFamily() {
return MY_FAMILY;
}
public MyDataTable() throws ClassNotFoundException, SQLException {
setRendererType(MY_RENDERER_TYPE);
db = new DataBaseManagement("jdbc:mysql://localhost:3306/fakulte", "root", "");
}
public String getTitle() {
return Title;
}
public void setTitle(String Title) {
this.Title = Title;
}
public String[] getColumnnames() {
return columnnames;
}
public void setColumnnames(String[] columnnames) {
this.columnnames = columnnames;
}
public String[][] getData() {
return data;
}
public void setData(String[][] data) {
this.data = data;
}
public void executeQuery(String query) throws SQLException {
ArrayList<HashMap<String, String>> result = db.getQuery(query);
Object cols[] = result.get(0).keySet().toArray();
columnnames = new String[cols.length];
data = new String[result.size()][cols.length];
for (int c = 0; c < cols.length; c++) {
columnnames[c] = cols[c].toString();
}
for (int r = 0; r < result.size(); r++) {
for (int c = 0; c < columnnames.length; c++) {
data[r][c] = result.get(r).get(columnnames[c]);
}
}
Title = db.getLastQueryTitle();
}
#Override
public Object saveState(FacesContext context) {
Object val[] = new Object[4];
val[0] = super.saveState(context);
val[1] = Title;
val[2] = columnnames;
val[3] = data;
return val;
}
#Override
public void restoreState(FacesContext context, Object state) {
Object val[] = (Object[]) state;
super.restoreState(context, val[0]);
Title = (String) val[1];
columnnames = (String[]) val[2];
data = (String[][]) val[3];
}
}
3) com.rendererwhich contains MyRendererrenderer class
package com.renderer;
import com.components.MyDataTable;
import java.io.IOException;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.render.FacesRenderer;
import javax.faces.render.Renderer;
#FacesRenderer(componentFamily = MyDataTable.MY_FAMILY,
rendererType = MyDataTable.MY_RENDERER_TYPE)
public class MyRenderer extends Renderer {
#Override
public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
super.encodeBegin(context, component);
if (component != null) {
encodeTable(context.getResponseWriter(), (MyDataTable) component);
}
}
#Override
public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
super.encodeEnd(context, component);
ResponseWriter out = context.getResponseWriter();
out.startElement("h3", component);
out.write("Sayfa Sonu-------");
out.endElement("h3");
}
private void encodeTable(ResponseWriter out, MyDataTable table) throws IOException {
if (table.getTitle() != null) {
out.startElement("h1", table);
out.write(table.getTitle());
out.endElement("h1");
}
if (table.getData() != null) {
out.startElement("table", table);
out.writeAttribute("border", "1", "border");
if (table.getColumnnames() != null) {
out.startElement("tr", table);
String col[] = table.getColumnnames();
for (int i = 0; i < col.length; i++) {
out.startElement("td", table);
out.write(col[i]);
out.endElement("td");
}
out.endElement("tr");
}
String data[][] = table.getData();
for (int r = 0; r < data.length; r++) {
out.startElement("tr", table);
for (int c = 0; c < data[r].length; c++) {
out.startElement("td", table);
out.write(data[r][c]);
out.endElement("td");
}
out.endElement("tr");
}
out.endElement("table");
}
}
}
When I include this jar library in another project as follows:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:t="http:java.sun.com/MyDataTableTag">
<head>
<title>TODO supply a title</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<h:form>
<h:inputText binding="#{Bean.input}"/>
<h:commandButton value="Execute query" action="#{Bean.executeQuery()}"/>
<t:MyDataTableTag title="Hello" binding="#{Bean.table}"/>
</h:form>
</body>
</html>
Expression Error: Named Object: com.components.MyDataTable not found.error message is thrown.
I am using NetBeans 8.0. I need help.
Thank you BalusC
I put new DataBaseManagement() in try-catch but no exception was thrown. I removed <rtexprvalue>and <deferred-value>attributes from tag lib.xmland nothing changed. Stack trace is as follows:
javax.faces.FacesException: Expression Error: Named Object: com.components.MyDataTable not found.
at com.sun.faces.application.ApplicationImpl.createComponentApplyAnnotations(ApplicationImpl.java:1933)
at com.sun.faces.application.ApplicationImpl.createComponentApplyAnnotations(ApplicationImpl.java:1968)
at com.sun.faces.application.ApplicationImpl.createComponent(ApplicationImpl.java:1151)
at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.createComponent(ComponentTagHandlerDelegateImpl.java:499)
at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:172)
at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:120)
at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:95)
at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:137)
at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:190)
at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:120)
at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:95)
at com.sun.faces.facelets.compiler.NamespaceHandler.apply(NamespaceHandler.java:93)
at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:95)
at com.sun.faces.facelets.compiler.EncodingHandler.apply(EncodingHandler.java:87)
at com.sun.faces.facelets.impl.DefaultFacelet.apply(DefaultFacelet.java:161)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.buildView(FaceletViewHandlingStrategy.java:980)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:99)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
I solved the problem.
Do not forget to put an empty faces-config.xml file (containing only
<?xml version="1.0" encoding="UTF-8"?>
<faces-config
xmlns="java.sun.com/xml/ns/javaee"; xmlns:xsi="w3.org/2001/XMLSchema-instance"; xsi:schemaLocation="java.sun.com/xml/ns/javaee java.sun.com/xml/ns/javaee/web-facesconfig_2_1.xsd";
version="2.1">
</faces-config>
) in your META-INF package.

Logout SSL (JBoss AS 7.1, JDK 1.6 e JSF 2)

Good morning.
I have a problem when I try to perform logout in the authenticated system via a digital certificate.
To better describe the problem is as follows:
The browser presented the certificates for authentication check box, selecting and providing the PIN for the certificate selected the system performs login normally. The problem is when the user triggers the logout button, it invalidates the session and redirects to the login screen again. However when the user clicks the button that redirects to a restricted area the browser should resubmit the certificate selection box, but the same goes direct, using the certificate information selected in the previous login.
If we stop the server or close and open the browser it will prompt the choice of certificate again.
standalone.xml:
<subsystem xmlns="urn:jboss:domain:web:1.1" default-virtual-server="default-host" native="false">
<connector name="http" protocol="HTTP/1.1" scheme="http" socket-binding="http" redirect-port="8443"/>
<connector name="https" protocol="HTTP/1.1" scheme="https" socket-binding="https" secure="true">
<ssl key-alias="localhost" verify-client="true"/>
</connector>
<virtual-server name="default-host" enable-welcome-root="true">
<alias name="localhost"/>
<alias name="example.com"/>
</virtual-server>
web.xml:
<filter>
<filter-name>Authentication X509Certificate Filter</filter-name>
<filter-class>br.gov.sp.sefin.desif.security.servlet.AuthX509CertificateFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Authentication X509Certificate Filter</filter-name>
<url-pattern>/pages/*</url-pattern>
</filter-mapping>
<security-constraint>
<web-resource-collection>
<web-resource-name>pages/*</web-resource-name>
<url-pattern>/pages/*</url-pattern>
<http-method>GET</http-method>
</web-resource-collection>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
<login-config>
<auth-method>CLIENT-CERT</auth-method>
</login-config>
Filter authentication AuthX509CertificateFilter :
public class AuthX509CertificateFilter implements Filter {
private static final String MS_005 = "MS_005";
private static final String URI_DEFINIR_IF = "/internet/pages/home.xhtml";
private Principal authenticatedUser;
#Inject
private RepresentanteBO representanteBO;
#Inject
private InstituicaoFinanceiraBO instituicaoFinanceiraBO;
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
Object attrSessionValid = req.getSession().getAttribute("sessionValid");
Object attrSessionAuthenticated = req.getSession().getAttribute("authenticated");
Object attrSessionInstituicaoFinanceira = req.getSession().getAttribute("instituicaoFinanceiraInternet");
Boolean sessionValid = (Boolean) (attrSessionValid != null ? attrSessionValid : Boolean.FALSE);
Boolean sessionAuthenticated = (Boolean) (attrSessionAuthenticated != null ? attrSessionAuthenticated : Boolean.FALSE);
if(!sessionValid || (URI_DEFINIR_IF.equals(req.getRequestURI()) && attrSessionInstituicaoFinanceira == null)) {
X509Certificate certs[] = (X509Certificate[] )req.getAttribute("javax.servlet.request.X509Certificate");
if(certs != null) {
X509Certificate t = (X509Certificate) certs[0];
Principal subjectDN = t.getSubjectDN();
authenticatedUser = subjectDN;
sessionAuthenticated = validarAutenticacao(subjectDN, req, resp);
chain.doFilter(new HttpServletRequestWrapper(req) {
#Override
public Principal getUserPrincipal() {
return authenticatedUser;
}
}, response);
}
} else {
Principal userPrincipal = req.getUserPrincipal();
if(userPrincipal != null) {
sessionAuthenticated = validarAutenticacao(userPrincipal, req, resp);
}
chain.doFilter(new HttpServletRequestWrapper(req) {
#Override
public Principal getUserPrincipal() {
return authenticatedUser;
}
}, response);
}
if(!resp.isCommitted() && !sessionAuthenticated) {
Object attribute = req.getSession().getAttribute("cpfCnpj");
if(attribute != null)
req.getSession().setAttribute(MS_005, MessagePtBrUtil.recupera(MS_005, UtilFormatter.formatarCPF((String) attribute)));
RequestDispatcher dispatcher = req.getRequestDispatcher("../login.xhtml");
dispatcher.forward(req, resp);
}
}
public void atualizarDadosDeSessao(HttpServletRequest req, Boolean sessionValid, Boolean sessionAuthenticated) {
req.getSession().setAttribute("sessionValid", sessionValid);
req.getSession().setAttribute("authenticated", sessionAuthenticated);
}
public Boolean validarAutenticacao(Principal userPrincipal, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Boolean sessionValid = Boolean.TRUE;
Boolean sessionAuthenticated = Boolean.TRUE;
String[] cn = userPrincipal.getName().split(",");
String cpfCnpj = cn[0].split(":")[1];
req.getSession().setAttribute("cpfCnpj", cpfCnpj);
BigInteger raizCnpj = new BigInteger(cpfCnpj.substring(0, 8));
if(cpfCnpj.length() == 14 && instituicaoFinanceiraBO.verificarInstituicaoFinanceiraRaizCnpj(raizCnpj)) {
RequestDispatcher dispatcher = req.getRequestDispatcher("../pages/home.xhtml");
dispatcher.forward(req, resp);
} else {
BigInteger cpf = new BigInteger(cpfCnpj);
if(representanteBO.verificarRepresentanteInstituicaoFinanceira(cpf)) {
RequestDispatcher dispatcher = req.getRequestDispatcher("../pages/autenticarusuario/definirInstituicaoFinanceira.xhtml?cpf="+cpf);
dispatcher.forward(req, resp);
} else { // não tem instituição financeira vinculada ao CPF
sessionValid = Boolean.FALSE; sessionAuthenticated = Boolean.FALSE;
}
}
atualizarDadosDeSessao(req, sessionValid, sessionValid);
return sessionValid && sessionAuthenticated;
}
#Override
public void destroy() {
}
}
Logout method:
public void sair() {
ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
this.inserirLogAuditoriaLogout();
context.invalidateSession();
HttpServletRequest request = (HttpServletRequest) context.getRequest();
request.getSession().setAttribute("sessionValid", Boolean.FALSE);
request.getSession().setAttribute("authenticated", Boolean.FALSE);
try {
request.logout();
context.redirect("/internet/login.xhtml");
} catch (IOException e) {
new IOException();
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I've tried using some javascript solutions to perform the cleaning of the certificate for authentication data stored in the browser. Example:
window.crypto.logout();
document.execCommand("ClearAuthenticationCache");
function logOut()
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.timeout = 2000; // 2 seconds
xmlHttp.onreadystatechange = function ()
{
if (xmlHttp.readyState == 4)
{
console.log("status: "+xmlHttp.status);
console.log("response: '"+xmlHttp.responseText+"'");
}
};
xmlHttp.open("GET", "/internet/login.xhtml", true);
xmlHttp.send();
}
But did not work.
Please if anyone has been there and succeeded in solve it present your solution.
I hope I can have been clear in the description of the problem. I am available to best describes it.
I thank you so much attention.

javax.servlet.ServletException at javax.faces.webapp.FacesServlet.service(FacesServlet.java:321)

I am working with JSF 2.0, tomcat 7.0, mojarra 2.0.3 and primefaces.
The problem is that I implemented unsuccessfully javax.servlet.Filter class to redirect to the login page if a user tries to enter a page without having logged in, but I am also using FileUpload to upload files to server, which I think is what is me and trigger conflict with the doFilter method, the server throws me the following exception:
javax.servlet.ServletException
javax.faces.webapp.FacesServlet.service (FacesServlet.java: 321)
org.primefaces.webapp.filter.FileUploadFilter.doFilter (FileUploadFilter.java: 98)
org.apache.tomcat.websocket.server.WsFilter.doFilter (WsFilter.java: 52)
I configured the web.xml file as follows:
<!--this may be the cause of the error--!>
<filter>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
<filter>
<filter-name>Login</filter-name>
<filter-class>controller.BeanFiltersession</filter-class>
</filter>
<filter-mapping>
<filter-name>Login</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
after that delete the class that implemented Filter and erased the lines in the web.xml file, but the error still persists
any idea how to fix it?
the problem is not the FileUpload problem is between primefaces, I think the problem is that as I indicated one filter to validate sessions using HttpSession and HttpServletRequest, upon login sends me this exception, it is clear that delete the class that implemented Filter, probe the FileUpload and works without problems, but I think the changes I made in that class were recorded at api.jar servlet-api having Tomcat 7.0 my code is as follows:
package validators;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
public class SessionValidator {
public static HttpSession getSesion(){
return (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
}
public static HttpServletRequest getRequest(){
return (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
}
public static String getUser(){
HttpSession sesion= (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
return sesion.getAttribute("usuario").toString();
}
public static String getNivel(){
HttpSession sesion=getSesion();
if(sesion !=null){
return sesion.getAttribute("nivel").toString();
}else{
return null;
}
}
}
The SessionValidator class called when I login in my code is this:
package controller;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.http.HttpSession;
import org.primefaces.context.RequestContext;
import validators.SessionValidator;
import model.csConexion;
import model.csSesion;
#ManagedBean
#SessionScoped
public class BeanSesion implements Serializable{
private static final long serialVersionUID = 1L;
private csSesion sesion;
private csConexion con;
HttpSession session;
private String usuario;
private String nivel;
public BeanSesion(){
sesion=new csSesion();
con=new csConexion();
}
public String getUsuario(){
return SessionValidator.getUser();
}
public void setUsuario(String usuario){
this.usuario=usuario;
}
public String getNivel(){
if(SessionValidator.getSesion().getAttribute("usuario")!=null){
return SessionValidator.getNivel();
}else{
return "";
}
}
public void setNivel(String nivel){
this.nivel=nivel;
}
public csSesion getSesion(){
return sesion;
}
public void setSesion(csSesion sesion){
this.sesion=sesion;
}
public String iniciarsesion(ActionEvent e){
RequestContext context= RequestContext.getCurrentInstance();
FacesContext fcontext= FacesContext.getCurrentInstance();
FacesMessage message=null;
boolean ok=false;
ResultSet rs;
try {
if(con.conectar()==true){
String sql="select*from usuario where usuario=? and contrasenia=?";
PreparedStatement comando= con.getConexion().prepareStatement(sql);
comando.setString(1,sesion.getUsuario());
comando.setString(2,sesion.getContrasenia());
rs=comando.executeQuery();
if(rs.next()){
nivel= rs.getString("nivel");
usuario= rs.getString("usuario");
ok=true;
session= SessionValidator.getSesion();
session.setAttribute("usuario", usuario);
session.setAttribute("nivel", nivel);
message= new FacesMessage(FacesMessage.SEVERITY_INFO,"¡Bienvenido!",sesion.getUsuario());
try {
if(nivel.equals("master")){
fcontext.getExternalContext().redirect("admin/admin.xhtml");
}else if(nivel.equals(null)){
fcontext.getExternalContext().redirect("index.xhtml");
}
} catch (Exception e2) {
e2.printStackTrace();
message= new FacesMessage(FacesMessage.SEVERITY_WARN,"Error","Error");
}
}else{
ok=false;
message= new FacesMessage(FacesMessage.SEVERITY_ERROR,"Error","Usuario o contraseña inválidos");
}
FacesContext.getCurrentInstance().addMessage(null,message);
context.addCallbackParam("Ok", ok);
}
} catch (Exception ex) {
ex.printStackTrace();
ok=false;
}
finally{
System.out.println(nivel);
con.desconectar();
}
return nivel;
}
}
and this is the exception send Tomcat:
excepción
javax.servlet.ServletException: null source
javax.faces.webapp.FacesServlet.service(FacesServlet.java:321)
org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:98)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
causa raíz
java.lang.IllegalArgumentException: null source
java.util.EventObject.<init>(Unknown Source)
javax.faces.event.SystemEvent.<init>(SystemEvent.java:67)
javax.faces.event.ComponentSystemEvent.<init>(ComponentSystemEvent.java:69)
javax.faces.event.PostRestoreStateEvent.<init>(PostRestoreStateEvent.java:69)
com.sun.faces.lifecycle.RestoreViewPhase.deliverPostRestoreStateEvent(RestoreViewPhase.java:256)
com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:245)
com.sun.faces.lifecycle.Phase.doPhase(Phase.java:97)
com.sun.faces.lifecycle.RestoreViewPhase.doPhase(RestoreViewPhase.java:107)
com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:114)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:308)
org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:98)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

ManagedBeanCreationException issue while setting up for JSF/j_security_check test

I'm hoping someone can give me a hint at what's going on here with this exception. I'm putting together an environment where i can test out j_security_check with JSF and what I'm noticing is when i redeploy my application without restarting glassfish i see this error. I thought it would be perfectly safe to just redeploy the war but my setup is hosed until glassfish is restarted and war redeployed. I'm worried that this will becomes an issue later down the road. Any advise?
I'm using Glassfish 3.1.2, NetBeans 7.1.2...
com.sun.faces.mgbean.ManagedBeanCreationException: An error occurred performing resource injection on managed bean userController
at com.sun.faces.mgbean.BeanBuilder.invokePostConstruct(BeanBuilder.java:229)
at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:105)
at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:409)
at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:269)
at com.sun.faces.el.ManagedBeanELResolver.resolveBean(ManagedBeanELResolver.java:244)
at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:116)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at com.sun.el.parser.AstIdentifier.getValue(AstIdentifier.java:103)
at com.sun.el.parser.AstValue.getValue(AstValue.java:179)
at com.sun.el.parser.AstDeferredExpression.getValue(AstDeferredExpression.java:63)
at com.sun.el.parser.AstCompositeExpression.getValue(AstCompositeExpression.java:68)
at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:224)
at org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
at javax.faces.component.UIOutput.getValue(UIOutput.java:169)
at com.sun.faces.renderkit.html_basic.OutputLinkRenderer.getValue(OutputLinkRenderer.java:182)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:355)
at com.sun.faces.renderkit.html_basic.OutputLinkRenderer.renderAsActive(OutputLinkRenderer.java:191)
at com.sun.faces.renderkit.html_basic.OutputLinkRenderer.encodeBegin(OutputLinkRenderer.java:107)
at javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:820)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1755)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:402)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:288)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1542)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:849)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:746)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1045)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:228)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:662)
Caused by: com.sun.faces.spi.InjectionProviderException: com.sun.enterprise.container.common.spi.util.InjectionException: Exception attempting invoke lifecycle method private void avenger.UserController.startup()
at org.glassfish.faces.integration.GlassFishInjectionProvider.invokePostConstruct(GlassFishInjectionProvider.java:231)
at com.sun.faces.mgbean.BeanBuilder.invokePostConstruct(BeanBuilder.java:223)
... 56 more
Caused by: com.sun.enterprise.container.common.spi.util.InjectionException: Exception attempting invoke lifecycle method private void avenger.UserController.startup()
at org.glassfish.faces.integration.GlassFishInjectionProvider.invokeLifecycleMethod(GlassFishInjectionProvider.java:393)
at org.glassfish.faces.integration.GlassFishInjectionProvider.invokePostConstruct(GlassFishInjectionProvider.java:306)
at org.glassfish.faces.integration.GlassFishInjectionProvider.invokePostConstruct(GlassFishInjectionProvider.java:229)
... 57 more
Caused by: java.security.PrivilegedActionException: java.lang.reflect.InvocationTargetException
at java.security.AccessController.doPrivileged(Native Method)
at org.glassfish.faces.integration.GlassFishInjectionProvider.invokeLifecycleMethod(GlassFishInjectionProvider.java:376)
... 59 more
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.glassfish.faces.integration.GlassFishInjectionProvider$2.run(GlassFishInjectionProvider.java:382)
... 61 more
Caused by: java.lang.ClassCastException: avenger.MyUser cannot be cast to avenger.MyUser
at avenger.UserController.updateUserList(UserController.java:103)
at avenger.UserController.startup(UserController.java:39)
Here are portions of my web.xml
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.xhtml</welcome-file>
</welcome-file-list>
<security-constraint>
<display-name>Admin</display-name>
<web-resource-collection>
<web-resource-name>Admin Views</web-resource-name>
<description/>
<url-pattern>/admin/*</url-pattern>
</web-resource-collection>
</security-constraint>
<security-role>
<description/>
<role-name>ADMIN</role-name>
</security-role>
<security-role>
<description/>
<role-name>USER</role-name>
</security-role>
my management bean
#ManagedBean(eager = true)
#SessionScoped
public class UserController implements Serializable {
/**
* Creates a new instance of UserBean
*/
public UserController() {}
#PostConstruct
private void startup() {
System.out.println("inilitiazing UserController");
updateUserList();
}
#PreDestroy
private void shutdown() {
System.out.println("destroying UserController");
Utils.stopEntityManager();
}
private static final long serialVersionUID = 1L;
#Override
public int hashCode() {
int hash = 5;
hash = 67 * hash + (this.userList != null ? this.userList.hashCode() : 0);
hash = 67 * hash + (this.cUser != null ? this.cUser.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final UserController other = (UserController) obj;
if (this.userList != other.userList && (this.userList == null || !this.userList.equals(other.userList))) {
return false;
}
if (this.cUser != other.cUser && (this.cUser == null || !this.cUser.equals(other.cUser))) {
return false;
}
return true;
}
//the current user
MyUser cUser = new MyUser();
public MyUser getMyUser() { return cUser; }
public void setMyUser(MyUser cUser) {this.cUser = cUser;}
//the new user
MyUser nUser = new MyUser();
public MyUser getNewUser() { return nUser; }
public void setNewUser(MyUser nUser) {this.nUser = nUser;}
// list of current users
List userList = new LinkedList();
public void setUserList(List uList) {userList = uList;}
public List getUserList() {return userList;}
public String updateUserList() {
System.out.println("updateUserList()" );
EntityManager em = Utils.getEntityManager();
//Query q = em.createNamedQuery("MyUser.findAll");
Query q = em.createQuery("Select u FROM MyUser u", MyUser.class);
userList = q.getResultList();
for (MyUser cu : userList) {
String groupList = "";
for (Grouptable gt : cu.getGrouptableList()) {
groupList += ":"+gt.getGrouptablePK().getGroupid();
}
cu.setGrouplist(groupList);
}
return "users.xhtml";
}
public boolean usernameExist() {
return false;
}
public String resetNewUser() {
nUser = new MyUser();
return "createuser.xhtml";
}
public String createNewUser () {
System.out.println("attempting to create account with\n"
+ "\tusername: " + nUser.getUsername() +"\n"
+ "\tpassword: "+nUser.getPassword() +"\n"
+ "\tfirst name: "+nUser.getFirstName()+"\n"
+ "\tlast name: "+nUser.getLastName()+"\n");
//TODO: check if newUser already exist if so send message to user
// set the hashed password
MessageDigest md = null;
byte [] digest;
try { md = MessageDigest.getInstance("MD5"); }
catch (NoSuchAlgorithmException ex) {
Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("nUser"+nUser);
//System.out.println("cUser.password"+cUser.getPassword());
digest = md.digest(nUser.getPassword().getBytes());
nUser.setPassword(Utils.toHex(digest));
System.out.println("creating user: " + nUser.getUsername() +
" password: "+nUser.getPassword());
EntityManager em = Utils.getEntityManager();
em.getTransaction().begin();
em.persist(nUser);
em.getTransaction().commit();
updateUserList();
return "users.xhtml";
}
public String deleteUser () {
System.out.println("deleting user: "+cUser.getUsername());
EntityManager em = Utils.getEntityManager();
cUser = em.find(MyUser.class, cUser.getUsername());
em.getTransaction().begin();
em.remove(cUser);
em.getTransaction().commit();
//em.close();
return "users.xhtml";
}
public String deleteSelectedUsers () {
for (MyUser cu : userList) {
if (cu.getSelected()) {
System.out.println("Planning to remove: "+cu);
}
}
EntityManager em = Utils.getEntityManager();
for (MyUser cu : userList) {
if (cu.getUsername().equalsIgnoreCase("ADMIN") && cu.getSelected()) {
System.out.println("admin account can not be deleted");
continue;
}
if (cu.getSelected()) {
MyUser targetUser = em.find(MyUser.class, cu.getUsername());
System.out.println("removing user: "+cu.toString());
em.getTransaction().begin();
em.remove(targetUser);
em.getTransaction().commit();
}
}
updateUserList();
return "users.xhtml";
}
public String login() {
System.out.println("user attempting to login...");
System.out.println("username: "+cUser.getUsername());
System.out.println("password: "+cUser.getPassword());
// set the hashed password
MessageDigest md = null;
byte [] digest;
try { md = MessageDigest.getInstance("MD5"); }
catch (NoSuchAlgorithmException ex) {
Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
}
digest = md.digest(cUser.getPassword().getBytes());
cUser.setPassword(Utils.toHex(digest));
MyUser userFound = Utils.getEntityManager().find(MyUser.class, cUser.getUsername());
if (userFound == null) {
System.err.println("user does not exist");
return null;
}
if (!userFound.getPassword().equalsIgnoreCase(cUser.getPassword())) {
System.err.println("Incorrect Password");
return null;
}
return "users.xhtml";
// FacesContext context = FacesContext.getCurrentInstance();
// HttpServletRequest request = (HttpServletRequest) context.getExternalContext();
// try {
// request.login(this.cUser.getFirstName(), this.cUser.getPassword());
// this.cUser = Utils.getEntityManager().find(MyUser.class,this.cUser.getUsername());
// } catch (ServletException e) {
// context.addMessage(null, new FacesMessage("Unknown login"));
// }
}
public MyUser getUser() {
if (cUser==null) {
Principal principal = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
if (principal != null) {
//cUser = userDAO.find(principal.getName()); // Find User by j_username
cUser = Utils.getEntityManager().find(MyUser.class, principal.getName());
}
}
return cUser;
}
}
my init.sql for JavaDB
create table usertable (
username varchar(128) NOT NULL CONSTRAINT USER_PK PRIMARY KEY ,
password varchar(128) NOT NULL,
firstname varchar(128) NOT NULL,
lastname varchar(128) NOT NULL
);
create table grouptable(
username varchar(128) NOT NULL,
groupid varchar(128) NOT NULL,
CONSTRAINT GROUP_PK PRIMARY KEY(username, groupid),
CONSTRAINT USER_FK FOREIGN KEY(username) REFERENCES usertable(username)
ON DELETE CASCADE ON UPDATE RESTRICT
);
insert into usertable(username,password,firstname,lastname)
values ('admin', '21232f297a57a5a743894a0e4a801fc3','','');
insert into grouptable(username,groupid) values ('admin', 'USER');
insert into grouptable(username,groupid) values ('admin', 'ADMIN');
i created my connection pool and jdbcRealm using instructions from:
http://blog.gamatam.com/2009/11/jdbc-realm-setup-with-glassfish-v3.html

Resources