Исключение при обработке события типа AFTER_FILTER_EVENT - PullRequest
1 голос
/ 10 февраля 2012

Я гуглял это так много раз сейчас, без всякой удачи. Надеюсь, вы сможете мне помочь.

У меня есть веб-проект, который использует JSF Mojarra 2.1, Primefaces 3.1. Проект использует Spring Security для обработки аутентификации.

Проект выполняется на Glassfish 3.1.1, поэтому я использую предоставленную версию JSF.

Проблема в том, что после входа в систему я получаю следующее исключение при отображении страницы main.xhtml.

java.lang.RuntimeException: WEB5001: Exception during processing of event of type AFTER_FILTER_EVENT for web module StandardEngine[glassfish-web].StandardHost[server].StandardContext[/sormAdmin2]
at com.sun.web.server.J2EEInstanceListener.handleAfterEvent(J2EEInstanceListener.java:344)
at com.sun.web.server.J2EEInstanceListener.instanceEvent(J2EEInstanceListener.java:112)
at org.apache.catalina.util.InstanceSupport.fireInstanceEvent(InstanceSupport.java:314)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:273)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
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 com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:330)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:174)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:828)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:725)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1019)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
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)

Вызывается: org.glassfish.api.invocation.InvocationException в org.glassfish.api.invocation.InvocationManagerImpl.postInvoke (InvocationManagerImpl.java:190) в com.sun.web.server.J2EEInstanceListener.handleAfterEvent (J2EEInstanceListener.java:339) ... еще 28

На странице входа в систему:

$<h:panelGrid columns="2" cellpadding="5" styleClass="messageGrid">
                    <h:outputLabel for="username" value="Username:" />
                    <p:inputText value="#{loginBean.username}" id="username"
                        required="true" label="username" />

                    <h:outputLabel for="password" value="Password:" />
                    <p:password value="#{loginBean.password}" id="password"
                        required="true" label="password" feedback="false" />

                    <f:facet name="footer">
                        <p:commandButton value="Login"
                            action="#{loginBean.login}" />
                    </f:facet>
                    <h:messages></h:messages>
                </h:panelGrid>

LoginBean:

package this.is.my.mb;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import this.is.my.ejb.beans.session.remote.UserRemote;
import this.is.my.ejb.ejb.vo.User;
import this.is.my.utils.EJBHandler;

import org.apache.commons.lang.NotImplementedException;
import org.primefaces.component.layout.LayoutUnit;
import org.primefaces.context.RequestContext;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

@ManagedBean(name = "loginBean", eager=true)
@SessionScoped
public class LoginBean implements Serializable {

  @PostConstruct
  public void init() {

    //checkUser();
  }

  /**
   * 
   */
  private static final long serialVersionUID = 1L;
  private UserRemote userRemote;
  private User user;
  private String username;

  private String password;

  public LoginBean() {
    layoutCenter = new LayoutUnit();
    layoutLeft = new LayoutUnit();
    layoutRight = new LayoutUnit();
    //layoutLogin = new LayoutUnit();
  }

  public String login() {
    FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Welcome", getUsername());  
    boolean loggedIn = true;  
    String redirectTo = "/user/main.xhtml?faces-redirect=true";
    try {
      EJBHandler ejbHandler2 = new EJBHandler();
      userRemote = ejbHandler2.getUserRemote();
      if(userRemote != null)
      user = userRemote.sjekkBruker(getUsername(), getPassword());        

      if(user != null) {
        System.out.println("User  != null: accessLevel: " + user.getAccessLevel());
        Authentication rfesult = new Authentication() {
          @Override
          public String getName() {
            // TODO Auto-generated method stub
            return username;
          }

          @Override
          public boolean isAuthenticated() {
            return true;
          }

          @Override
          public Object getPrincipal() {
            throw new NotImplementedException();
          }

          @Override
          public Object getDetails() {
            throw new NotImplementedException();
          }

          @Override
          public Collection<GrantedAuthority> getAuthorities() {
            GrantedAuthority ga = new GrantedAuthority() {
              private static final long serialVersionUID  = 1132123132132L;

              @Override
              public String getAuthority() {
                return "ROLE_USER";
              }
            };          

            GrantedAuthority g2a = new GrantedAuthority() {
              private static final long serialVersionUID  = 1132123132132L;

              @Override
              public String getAuthority() {
                return "ROLE_STATS";
              }
            };

            GrantedAuthority g3a = new GrantedAuthority() {
              private static final long serialVersionUID  = 1132123132132L;

              @Override
              public String getAuthority() {
                return "ROLE_ADMIN";
              }
            };

            Collection<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
            if(user.getAccessLevel() == 3 || user.getAccessLevel() == 1) {
              list.add(ga);
            }
            if(user.getAccessLevel() == 2 || user.getAccessLevel() == 1) {
              list.add(g2a);
            }
            if(user.getAccessLevel() == 1) {
              list.add(g3a);
            }
            return list;
          }

          @Override
          public Object getCredentials() {
            throw new NotImplementedException();
          }

          @Override
          public void setAuthenticated(boolean arg0) throws IllegalArgumentException {
            throw new NotImplementedException();
          }

        };
        checkUser();
        SecurityContextHolder.getContext().setAuthentication(rfesult);

        if(user.getAccessLevel() == 2) { // user only has access to statistics
          redirectTo = "/stats/getstats.jsf?faces-redirect=true";   
        }
        if(user.getAccessLevel() < 1) {
          redirectTo = "/login/login.xhtml?faces-redirect=true";
          msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Login failed", "Wrong username and/or password");
          loggedIn = false;
        }
      } else {
        msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Login failed", "Wrong username and/or password");
        loggedIn = false;
        redirectTo = null;
        System.out.println("User  == null");
      }

    } catch (SQLException e) {
      e.printStackTrace();
    }
    FacesContext.getCurrentInstance().addMessage(null, msg);  

    RequestContext context = RequestContext.getCurrentInstance();  
    if(context != null)
    context.addCallbackParam("loggedIn", loggedIn);
    System.out.println(redirectTo);
    return redirectTo;
  }

  public User getUser() {
    return user;
  }

  public void setUser(User user) {
    this.user = user;
  }

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }


  public String getUsername() {
    checkUser();
    return username;}}

Мой web.xml:

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
  http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  id="WebApp_ID" version="2.5">

  <display-name>JavaServerFaces</display-name>  

  <!-- Change to "Production" when you are ready to deploy -->
  <context-param>
    <param-name>javax.faces.PROJECT_STAGE</param-name>
    <param-value>Development</param-value>
  </context-param>

  <!-- for EL 2.2-->
  <context-param>
    <param-name>com.sun.faces.expressionFactory</param-name>
    <param-value>com.sun.el.ExpressionFactoryImpl</param-value>
  </context-param>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/applicationContext*.xml
        </param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
    </listener>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

  <error-page>
    <exception-type>javax.faces.application.ViewExpiredException</exception-type>
    <location>/login.xhtml</location>
  </error-page>

  <session-config>
    <session-timeout>300</session-timeout>
  </session-config>

  <context-param>
    <param-name>javax.faces.DEFAULT_SUFFIX</param-name>
    <param-value>.xhtml</param-value>
  </context-param>

  <!-- Welcome page -->
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

  <!-- JSF mapping -->
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <!-- Map these files with JSF -->
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.jsf</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.faces</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
  </servlet-mapping>
  <context-param>
    <param-name>primefaces.THEME</param-name>
    <param-value>redmond</param-value>
  </context-param>
  <mime-mapping>
    <extension>png</extension>
    <mime-type>image/png</mime-type>
  </mime-mapping>

</web-app>

1 Ответ

0 голосов
/ 21 июня 2013

Я столкнулся с той же проблемой, и причина была в том, что пользовательские данные или информация, которые я передал в свой возвращенный токен (экземпляр UsernamePasswordAuthenticationToken), не реализовали UserDetails Spring Security (или расширили User).

Мое решение было:

1) Мой пользовательский провайдер аутентификации:

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
...
    @Override
    public Authentication authenticate(Authentication authentication) {
        ...
        MyUserLoginDetails loginUser = new MyUserLoginDetails(username,
            password, isActive, true, true, true, authorities, userId);
        ...
        return new UsernamePasswordAuthenticationToken(loginUser, null, authorities);
    }
}

2) Расширение класса входа в систему моего пользователя org.springframework.security.core.userdetails.User:

public class MyUserLoginDetails extends User {

    /**
     * Auto-generated serialVersionUID
     */
    private static final long serialVersionUID = -7045871751446202245L;

    private Long userId;

    public MyUserLoginDetails(String username, String password,
            boolean enabled, boolean accountNonExpired,
            boolean credentialsNonExpired, boolean accountNonLocked,
            Collection<? extends GrantedAuthority> authorities, Long userId) {
        super(username, password, enabled, accountNonExpired, credentialsNonExpired,
                accountNonLocked, authorities);
        this.userId = userId;
    }

    public Long getUserId() {
        return userId;
    }
    public void setUserId(Long userId) {
        this.userId = userId;
    }

}
...