Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.cfs.backingbean; import com.cfs.util.FacesUtil; import java.io.Serializable; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.faces.event.PhaseEvent; import javax.servlet.RequestDispatcher; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.WebAttributes; /** * * @author cfsbs_000 */ @ManagedBean(name = "BeanAutenticacao") @RequestScoped public class AutenticacaoBacking implements Serializable { boolean validaAdministrador = false; public AutenticacaoBacking() { init(); } public void init() { if (SecurityContextHolder.getContext().getAuthentication().getAuthorities().toString() .equals("[ADMINISTRADOR]")) { validaAdministrador = true; } } // @Autowired // private UserSession session; public String logar() { 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(); } catch (Exception ex) { FacesUtil.exibirMensagemErro(ex.getMessage()); return null; } return null; } public String deslogar() { SecurityContextHolder.clearContext(); FacesContext.getCurrentInstance().getExternalContext().invalidateSession(); return "/login.xhtml?faces-redirect=true"; } public void beforePhase(final PhaseEvent arg0) { Exception e = (Exception) FacesContext.getCurrentInstance().getExternalContext().getSessionMap() .get(WebAttributes.AUTHENTICATION_EXCEPTION); if (e instanceof BadCredentialsException) { FacesContext.getCurrentInstance().getExternalContext().getSessionMap() .put(WebAttributes.AUTHENTICATION_EXCEPTION, null); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Invalid username or password", null)); } } public boolean isValidaAdministrador() { return validaAdministrador; } public void setValidaAdministrador(boolean validaAdministrador) { this.validaAdministrador = validaAdministrador; } }