Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7159041
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T13:09:54+00:00 2026-05-28T13:09:54+00:00

I’m using spring security 3 in my jsf2 web app. How can I show

  • 0

I’m using spring security 3 in my jsf2 web app.

How can I show a bad credential message in my login form without appending a get param ?login_error to the authenticated-fail-login-page?

I’ve tried using a phase listener like this tutorial says:

http://tutorials.slackspace.de/tutorial/Custom-login-page-with-JSF-and-Spring-Security-3

But it doesn’t work.

Neither with a preRenderView listener.

And neither checking the spring security last exception for rendering the message.

Any ideas?

UPDATE:

My login page:

<f:metadata>
<f:viewParam name="error" value="#{autenticacionController.error}" />
<f:event listener="#{autenticacionController.comprobarAuthException}" type="preRenderView" />
</f:metadata>
<h:messages globalOnly="true" layout="table" />
<h:form id="formLogin" prependId="false">
<h:outputLabel for="j_username" value="Usuario:" />
<h:inputText id="j_username" value="#{autenticacionController.administrador.login}" />
<h:outputLabel for="j_password" value="Contraseña:" />
<h:inputSecret id="j_password" value="#{autenticacionController.administrador.password}" />
<h:commandButton value="Entrar" action="#{autenticacionController.loginAction}" />
<h:commandButton value="Cancelar" immediate="true" action="#{autenticacionController.cancelarAction}" />
</h:form>

My managed bean:

@ManagedBean(name="autenticacionController")
@RequestScoped
public class AutenticacionController extends BaseController {

    //entidad "administrador" contra el que validar los campos del form login
    private Administrador administrador = new Administrador();

    //propiedad de spring-security (true si el usuario no es anónimo)
    @SuppressWarnings("unused")
    private boolean autenticado;

    //propiedad para guardar el param GET si hubo fallo en la autenticación de SS
    private int error;

    //Constructor vacío del Backing Bean controlador
    public AutenticacionController() {
        log.info("Creación del backing bean AutenticacionController");
    }

    @PostConstruct
    public void init() {
        //inicializar atributos del backing bean
        log.info("PostConstruct del backing bean BarcoController");
    }


    //Getters y setters de atributos del backing bean
    public Administrador getAdministrador() {
        return administrador;
    }
    public void setAdministrador(Administrador administrador) {
        this.administrador = administrador;
    }

    public boolean isAutenticado() {
        Authentication autenticacion = SecurityContextHolder.getContext().getAuthentication();
        boolean resultado = (autenticacion != null) &&
                            !(autenticacion instanceof AnonymousAuthenticationToken) &&
                            autenticacion.isAuthenticated();
        return resultado;
    }

    public int getError() {
        return error;
    }
    public void setError(int error) {
        this.error = error;
    }

    //MÉTODO LISTENER del evento preRenderView en la página login.
    //Para comprobar si la autenticación de Spring Security falló (error=1).
    //En ese caso muestra el error con un faces message.
    public void comprobarAuthException (ComponentSystemEvent event){
        log.info("listener comprobarAuth");
        if (error==1) {
            String msj = "";
            Exception e = (Exception) UtilJsf.getParamSessionMap(WebAttributes.AUTHENTICATION_EXCEPTION);
            log.info("SSexception = "+((e==null)?"null":e.getMessage()));
            if (e != null) {
                String ultimoUsuario = (String) UtilJsf.getParamSessionMap(WebAttributes.LAST_USERNAME);
                log.info("SS last_username = "+ultimoUsuario);
                administrador.setLogin(ultimoUsuario);
                if (e instanceof BadCredentialsException) {
                    msj = UtilJsf.getMsjProperties("msjsInfo", "UsuPwdIncorrectos");
                } else {
                    msj = UtilJsf.getMsjProperties("msjsInfo", "ErrorAutenticacion");
                }
                UtilJsf.mostrarFacesMsjGlobal(msj);
            }
        }
        return;
    }


    /* ******************************* */
    /* Métodos "action" del form login */
    /* ******************************* */

    // EVENTO: Pulsar el botón "entrar" del form login
    // Reenviar(FORWARD) la petición a la URL "/j_spring_security_check" para autenticarse
    // También se debe configurar el filtro de spring-security para que procese forwards
    public void loginAction () {
        try {
            FacesContext.getCurrentInstance().getExternalContext().dispatch("/j_spring_security_check");
        } catch (IOException e) {
        }
    }

    // EVENTO: Pulsar el boton "cancelar" en el form login
    // No hacer nada --> Ir a la pantalla de inicio de la aplic
    public String cancelarAction () {
        return "/inicio";
    }

}

In my configuration of Spring Security I have:

authentication-failure-url="/faces/paginas/autenticacion/login.xhtml?error=1"

If I remove the error param, and the viewParam from the login page, and in the listener I just check for the Spring Security exception, it doesn’t work.

Thanks for the logout, my approach for it is similar, I have the following link for it:

<h:outputLink value="#{request.contextPath}/j_spring_security_logout" rendered="#{autenticacionController.autenticado}">Cerrar sesión (Administrador)</h:outputLink>
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T13:09:55+00:00Added an answer on May 28, 2026 at 1:09 pm

    I tend to use an <f:event> on preRenderView that will update the messages component on my form. This is how I did it.

    <f:event listener="#{loginBean.updateMessages(true)}" type="preRenderView" />
            <div style="margin-left: 50px; width: 500px;"><br />
            <h:form id="loginForm" prependId="false">
    
                <p:messages id="errorMessages" />
                <label for="j_username">
                    <h:outputText value="Username:" /><br />
                </label>
                <h:inputText id="j_username" required="true" width="500" style="width: 300px;" />
    
                <br />
                <br />
                <label for="j_password">
                    <h:outputText value="Password:" /><br />
                </label>
                <h:inputSecret id="j_password" required="true" width="500" style="width: 300px;" />
                &nbsp;<h:link value="Forgot my password" outcome="forgotpassword" /> 
                <br />
                <br />
                <label for="_spring_security_remember_me">
                    <h:outputText value="Remember me" />
                </label>
                <h:selectBooleanCheckbox id="_spring_security_remember_me" />
                <br /><br />
                <p:commandButton ajax="false" type="submit" id="login" action="#{loginBean.doLogin}" value="Login" update="errorMessages" />
            </h:form>
            </div>
    

    And then in my LoginBean managed bean, I forward the request onto the Spring Security servlet as so, and update the messages. You will notice that I also have code for a logout action if you are interested in seeing how I approached that problem as well.

    private String username;
    private String password;    
    
    public String getUsername() {
        return username;
    }
    
    public void setUsername(final String username) {
        this.username = username.trim();
    }
    
    public String getPassword() {
        return password;
    }
    
    public void setPassword(final String password) {
        this.password = password.trim();
    }
    
    public void updateMessages(boolean update) throws Exception {
        System.out.println("Start LoginBean.updateMessages");
        ex = (Exception)FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
            .get(WebAttributes.AUTHENTICATION_EXCEPTION);
    
    if (ex != null) {
        log.error("Authentication Failed! ", ex);
        System.err.println("Authentication Failed! " + ex.getMessage());
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), ex.getMessage()));
    }
        System.out.println("End LoginBean.updateMessages");
    }
    
    public String doLogin() {
        log.info("Start LoginBean.doLogin");
        try {
            ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
    
            RequestDispatcher dispatcher = ((ServletRequest) context.getRequest())
                     .getRequestDispatcher("/j_spring_security_check");
    
            dispatcher.forward((ServletRequest) context.getRequest(),
                    (ServletResponse) context.getResponse());
    
            FacesContext.getCurrentInstance().responseComplete();
            // It's OK to return null here because Faces is just going to exit.
        } catch (Exception e) {
            log.error("Exception doLogin", e);
        } finally {
            log.info("End LoginBean.doLogin");
        }
    return "";
    }
    
    public String logout() {
        FacesContext context = FacesContext.getCurrentInstance();
        Map<String, Object> sessionMap = context.getExternalContext().getSessionMap();
        if (!sessionMap.containsKey("sessionBean"))
            return "";
    
        SessionBean sessionBean = (SessionBean)sessionMap.get("sessionBean");
        log.info("Logging out user: " + sessionBean.getLoggedInUser().getUsername());
    
        sessionMap.remove("sessionBean");
    
        //HttpSession session = (HttpSession)context.getExternalContext().getSession(false);
        //session.invalidate();
    RequestDispatcher dispatcher = ((ServletRequest) context.getExternalContext().getRequest())
            .getRequestDispatcher("/j_spring_security_logout");
    
    try {
            dispatcher.forward((ServletRequest) context.getExternalContext().getRequest(),
                   (ServletResponse) context.getExternalContext().getResponse());
        } catch (ServletException e) {
            log.error("ServletException", e);
        } catch (IOException e) {
            log.error("IOException", e);
        }
    
    FacesContext.getCurrentInstance().responseComplete();
    // It's OK to return null here because Faces is just going to exit.
    
    log.info("End LoginBean.logout");       
    return "";
    }
    
    public boolean isLoggedIn() {
        FacesContext context = FacesContext.getCurrentInstance();
        Map<String, Object> sessionMap = context.getExternalContext().getSessionMap();
        return sessionMap.containsKey("sessionBean");
    }
    

    EDIT:

    I think I better understand your problem now. I remember that I had trouble getting this to work too, so basically I had to write my own class that implements AuthenticationFailureHandler and properly implement the method:

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) throws IOException, ServletException {
      //Do business logic stuff, logging, etc...
      request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, ex);
      response.sendRedirect("login.xhtml");
    

    Basically you see that I am instantiating an exception and setting it as a session attribute so that later in my managed bean it can be retrieved and converted into a FacesMessage.

    You will also have to declare this AuthenticationFailureHandler as a custom handler for authentication failure events in your Spring Security configuration file (Note that I am also showing that I do the same thing for an authentication success handler, but you may or may not want to do that as well).

    <form-login login-page="/login.xhtml" login-processing-url="/j_spring_security_check"
            authentication-success-handler-ref="authenticationSuccessBean"
            authentication-failure-handler-ref="authenticationFailureBean"  />
    
    ...
    <beans:bean id="authenticationFailureBean" class="com.maple.controllers.FailureHandler">
        <beans:property name="userBo" ref="userController" /> <!-- Just injecting my BL layer... -->
    </beans:bean>
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has
We're building an app, our first using Rails 3, and we're having to build
I am using Paperclip to handle profile photo uploads in my app. They upload
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a jquery bug and I've been looking for hours now, I can't
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
Seemingly simple, but I cannot find anything relevant on the web. What is the
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
We are using XSLT to translate a RIXML file to XML. Our RIXML contains

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.