How to implement LogoutFilter? - jsf

Hi guys I am building a Java web app using JSF. For authentication I have used Apache Shiro.I have built a logout button which is calling the logout method of shiro and then I redirect the user to login page. But If I click back button the user can navigate into pages. I read about this and I realized that I had to implement my own custom filter. This is the code of the filter :
import al.ikubinfo.ipermit.bpmn.model.entities.UserEntity;
import al.ikubinfo.ipermit.bpmn.services.UserService;
public class LoginFilter implements Filter {
private static final String LOGIN_VIEW = "/login.xhtml";
#EJB
private UserService userService;
#Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
UserEntity currentUser = userService.getCurrentUser();
if (currentUser == null) {
httpServletResponse.sendRedirect(httpServletRequest.getServletContext().getContextPath() + LOGIN_VIEW);
}
else {
chain.doFilter(request, response);
}
}
#Override
public void destroy() {
// TODO Auto-generated method stub
}
}
I have also included it in the web.xml but it doesnt work. The application start successfully but noe view is opened. Can someone help me please?

When using the back button you are seeing a cached version of the page. The page is cached locally in the browser.
After logout you must be going to login page
Use following javascript on this page
var url = window.location.href;
window.history.go(-window.history.length);
window.location.href = url;
Also try to insert
<META Http-Equiv="Cache-Control" Content="no-cache">
<META Http-Equiv="Pragma" Content="no-cache">
<META Http-Equiv="Expires" Content="0">
into jsp pages so that browser dont cache the pages.

Related

How to stop authorization WebFilter from redirecting me to homepage every time I invoke a request from another page

I am trying to build a simple Login/Signup Interface using JSF, Hibernate and WildFly. I have used the following AuthorizationFilter class so far in order to redirect to the login page if the session is not authenticated.
I also implemented a simple User CRUD view called
/admin.xhtml
which manages user entries in the DB. Now my problem is that every time I click a button to CRUD a User entry in admin.xhtml I am automatically redirected to the login page. When I disable this WebFilter everything works perfectly fine with the CRUD Interface.
How can I prevent this WebFilter from redirecting me after I have logged in and created a session?
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
#WebFilter(filterName = "AuthFilter", urlPatterns = { "*.xhtml" })
public class AuthorizationFilter implements Filter {
public AuthorizationFilter() {
}
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
try {
HttpServletRequest reqt = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
HttpSession ses = reqt.getSession(false);
String reqURI = reqt.getRequestURI();
if (reqURI.contains("/login.xhtml")
|| (ses != null && ses.getAttribute("username") != null)
|| reqURI.contains("/public/")
|| reqURI.contains("javax.faces.resource"))
chain.doFilter(request, response);
else
resp.sendRedirect(reqt.getContextPath() + "/faces/login.xhtml");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
#Override
public void destroy() {
}
}

Prevent users to manually access to page

i have implemented jsf phase listener which check if user looged in or not, and if not redirect user to login page.
Now, i want to implement phase listener in case where user manualy input
page name in address bar. In this case phase listener must automatic
redirect user to login page and destroy session.
How do that in JSF ?
Just use a simple servlet Filter which is mapped on a common URL pattern of the restricted pages like /app/*, /pages/*, /secured/*, etc. Here's a kickoff example assuming that you've a #SessionScoped #ManagedBean UserManager.
#WebFilter(urlPatterns={"/app/*"})
public class AuthenticationFilter implements Filter {
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession(false);
UserManager userManager = (session != null) ? (UserManager) session.getAttribute("userManager") : null;
if (userManager == null || !userManager.isLoggedIn()) {
response.sendRedirect(request.getContextPath() + "/login.xhtml"); // No logged-in user found, so redirect to login page.
} else {
chain.doFilter(req, res); // Logged-in user found, so just continue request.
}
}
// ...
}
I am on JSF 1.2 and did that this way:
public void beforePhase(PhaseEvent event)
{
FacesContext fCtx = FacesContext.getCurrentInstance();
String actualView = null;
actualView = event.getFacesContext().getApplication().getViewHandler().getResourceURL(fCtx, fCtx.getViewRoot().getViewId());
//actualView is the page the user wants to see
//you can check, if the user got the permission, is logged in, whatever
}
public PhaseId getPhaseId()
{
return PhaseId.RENDER_RESPONSE;
}

How to redirect to another page when already authenticated user accesses login page

I was wondering if it was possible to redirect users if a certain c:if clausule is true?
<c:if test="#{loginController.authenticated}">
//redirect to index page
</c:if>
Yes it is possible.
But, I would suggest you to apply filter for /login.jsp and in the filter forward to the other page if the user has already logged in.
Here is the example which tells how to do this using filter:
public class LoginPageFilter implements Filter
{
public void init(FilterConfig filterConfig) throws ServletException
{
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
{
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
if(request.getUserPrincipal() != null){ //If user is already authenticated
response.sendRedirect("/index.jsp");// or, forward using RequestDispatcher
} else{
filterChain.doFilter(servletRequest, servletResponse);
}
}
public void destroy()
{
}
}
Add this filter enty in the web.xml
<filter>
<filter-name>LoginPageFilter</filter-name>
<filter-class>
com.sample.LoginPageFilter
</filter-class>
<init-param>
<param-name>test-param</param-name>
<param-value>This parameter is for testing.</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>LoginPageFilter</filter-name>
<url-pattern>/login.jsp</url-pattern>
</filter-mapping>
Apart from the Filter approach, you can also use <f:event type="preRenderView">. Put this somewhere in top of the view:
<f:event type="preRenderView" listener="#{loginController.checkAuthentication}" />
And add this listener method to the LoginController:
public void checkAuthentication() throws IOException {
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
if (externalContext.getUserPrincipal() != null) {
externalContext.redirect(externalContext.getRequestContextPath() + "/index.xhtml");
}
}
That's all.
See also:
Is there any easy way to preprocess and redirect GET requests?

How do a web filter in JSF 2?

I create this filter :
public class LoginFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpSession session = req.getSession();
if (session.getAttribute("authenticated") != null || req.getRequestURI().endsWith("login.xhtml")) {
chain.doFilter(request, response);
} else {
HttpServletResponse res = (HttpServletResponse) response;
res.sendRedirect("login.xhtml");
return;
}
}
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void destroy() {
}
}
This is my structure:
And then I add the filter in the web.xml:
<filter>
<filter-name>LoginFilter</filter-name>
<filter-class>filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
The filter works as it should but keeps giving me this error:
"Was not possible find or provider the resource, login"
And after that my richfaces doesn't works anymore.
How can I solve that ? Or create a web filter correctly ?
Any path-relative URL (i.e. URLs which do not start with /) which you pass to sendRedirect() will be relative to the current request URI. I understand that the login page is at http://localhost:8080/contextname/login.xhtml. So, if you for example access http://localhost:8080/contextname/pages/user/some.xhtml, then this redirect call will actually point to http://localhost:8080/contextname/pages/user/login.xhtml, which I think don't exist. Look at the URL in your browser address bar once again.
To fix this problem, rather redirect to a domain-relative URL instead, i.e. start the URL with /.
res.sendRedirect(req.getContextPath() + "/login.xhtml");

JSF HTTP Session Login

I try to create login form in web application.
in JSP page I can use
<%
String name = request.getParameter( "username" );
session.setAttribute( "theName", name );
%>
but now I am using JSF /Facelets for web application
I don't know how to create session in JSF Backing bean for client and check if user is logged in or not so it will redirect into login page.
who can help me give me link tutorial for these problem ?
thank you before
Now I have little problem with mapping into web.xml
code snipped of class Filter
#Override
public void init(FilterConfig filterConfig) throws ServletException {
this.config = filterConfig;
}
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
LoginController controller = (LoginController) req.getSession()
.getAttribute("loginController");
if (controller == null || !controller.isLoggedIn()) {
res.sendRedirect("../admin/login.xhtml");
} else {
chain.doFilter(request, response);
}
}
and in web.xml I map with <fitler> tag
<filter>
<filter-name>userLoginFilter</filter-name>
<filter-class>com.mcgraw.controller.UserLoginFilter</filter-class>
<init-param>
<param-name>loginPage</param-name>
<param-value>/login.xhtml</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>userLoginFilter</filter-name>
<url-pattern>/admin/*</url-pattern>
</filter-mapping>
I have one folder admin in web project and I check if the user is not logged in with admin permission to not access page (I can do the permission check) but when I use the filter the browser doesn't understand url ??
no StackTrace show when the browser doesn't understand url
Error shown on Firefox
The page isn't redirecting properly
on IE it loading ... loading . .. non-stop
now I change condition which check if req.getPathInfo.startsWith("/login.xhtml") it will do chain
I have 2 idea but it response 500 HTTP STATUS
if (controller == null || !controller.isLoggedIn()) {
res.sendRedirect("../admin/login.xhtml");
if(req.getPathInfo().startsWith("/login.xhtml")){
chain.doFilter(request, response);
}
} else {
chain.doFilter(request, response);
}
===============
if (controller == null || !controller.isLoggedIn()) {
if (!req.getPathInfo().startsWith("/login.xhtml")) {
res.sendRedirect("../admin/login.xhtml");
} else {
chain.doFilter(request, response);
}
} else {
chain.doFilter(request, response);
}
======================
update Class loginController
package com.mcgraw.controller;
import com.DAO.UserBean;
import com.entity.IUser;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
/**
* #author Kency
*/
#ManagedBean
#SessionScoped
public class LoginController implements Serializable {
#EJB
private UserBean userBean;
private IUser user;
private boolean admin;
private boolean mod;
private PasswordService md5;
/** Creates a new instance of LoginController */
public LoginController() {
user = new IUser();
md5 = new PasswordService();
}
// getter / setter
public boolean isMod() {
return mod;
}
public void setMod(boolean mod) {
this.mod = mod;
}
public IUser getUser() {
return user;
}
public void setUser(IUser user) {
this.user = user;
}
public boolean isAdmin() {
return admin;
}
public void setAdmin(boolean admin) {
this.admin = admin;
}
public String cplogin() {
String md5Password = md5.md5Password(user.getPassword());
if (userBean.userLogin(user.getUsername(), md5Password) != null) {
if (user.getUsername() != null || md5Password != null) {
user = userBean.userLogin(user.getUsername(), md5Password);
if (user.getGroups().getAdmin() != null) {
setAdmin(user.getGroups().getAdmin());
}
if (user.getGroups().getMods() != null) {
setMod(user.getGroups().getMods());
}
if (isAdmin() == true || isMod() == true) {
return "home";
} else {
return "login";
}
} else {
return "login";
}
} else {
return "login";
}
}
public String logout() {
user = null;
return "login";
}
public boolean isLoggedIn() {
return user != null;
}
}
I have new problem if render JSF taglib with method loggedIn, in index page (not in admin folder) user doesn't login can see what I render example, <== this like if user doesn't login user can't see but why can he see it?
You can in JSF get/set HTTP session attributes via ExternalContext#getSessionMap() which is basically a wrapper around HttpSession#get/setAttribute().
#Named
#RequestScoped
public class LoginController {
private String username;
private String password;
#EJB
private UserService userService;
public String login() {
User user = userService.find(username, password);
FacesContext context = FacesContext.getCurrentInstance();
if (user == null) {
context.addMessage(null, new FacesMessage("Unknown login, try again"));
username = null;
password = null;
return null;
} else {
context.getExternalContext().getSessionMap().put("user", user);
return "userhome?faces-redirect=true";
}
}
public String logout() {
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
return "index?faces-redirect=true";
}
// ...
}
In the Facelets page, just bind the username and password input fields to this bean and invoke login() action accordingly.
<h:form>
<h:inputText value="#{loginController.username}" />
<h:inputSecret value="#{loginController.password}" />
<h:commandButton value="login" action="#{loginController.login}" />
</h:form>
Session attributes are directly accessible in EL. A session attribute with name user is in EL available as #{user}. When testing if the user is logged in some rendered attribute, just check if it's empty or not.
<h:panelGroup rendered="#{not empty user}">
<p>Welcome, #{user.fullName}</p>
<h:form>
<h:commandButton value="logout" action="#{loginController.logout}" />
</h:form>
</h:panelGroup>
The logout action basically just trashes the session.
As to checking an incoming request if a user is logged in or not, just create a Filter which does roughly the following in doFilter() method:
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession(false);
String loginURI = request.getContextPath() + "/login.xhtml";
boolean loggedIn = session != null && session.getAttribute("user") != null;
boolean loginRequest = request.getRequestURI().equals(loginURI);
boolean resourceRequest = request.getRequestURI().startsWith(request.getContextPath() + ResourceHandler.RESOURCE_IDENTIFIER);
if (loggedIn || loginRequest || resourceRequest) {
chain.doFilter(request, response);
} else {
response.sendRedirect(loginURI);
}
}
Map it on an url-pattern covering the restricted pages, e.g. /secured/*, /app/*, etc.
See also:
How to handle authentication/authorization with users in a database?
Authorization redirect on session expiration does not work on submitting a JSF form, page stays the same
Try this in your backing bean when a request is received (like in an action method):
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
HttpSession session = request.getSession();
Then you can work with the request and session objects just like you used to with JSPs, setting attributes and so on.
You might also want to take a look at my related question about checking the client session in a servlet Filter. You could write a similar Filter to check for the user login in their HttpSession and then do a redirect (or RequestDispatch like I ended up doing) to your login page if needed.

Resources