Prevent accessing restricted page without login in Jsf2
I have a problem. I want to prevent a user from accessing a page without login in jsf2. When a user d开发者_C百科irectly write restricted page url into browser, s/he should not see the page. Thats like above circumstance come about, s/he has to be redirected to login page. How can I do this programmatically ?
That depends on how you have programmed the login. You seem to be using homegrown authentication wherein you set the logged-in user as a property of a session scoped managed bean. Because with Java EE provided container managed login, preventing access to restricted pages is already taken into account.
Assuming that you've all restricted pages on a certain URL pattern, like /app/*
, /secured/*
etc and that your session scoped bean has the managed bean name user
, then you could use a filter for the job. Implement the following in doFilter()
method:
@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);
User user = (session != null) ? (User) session.getAttribute("user") : null;
if (user == null || !user.isLoggedIn()) {
response.sendRedirect("/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.
}
}
Map this filter on an URL pattern covering the restricted pages.
Further, you need to ensure that you've disabled the browser cache on those pages, otherwise the enduser will still be able to see them from browser cache after logout. You can also use a filter for this. You could even do it in the same filter. See also Browser back button doesn't clear old backing bean values.
have you tried writing a filter... you can intercept all calls check if the user has access to a page if not you can redirect the user to the login page...
精彩评论