Java filter for specific pages

1

How do I control access of pages with Java? I have a filter already implemented, which makes the control whether the user is logged in or not.

However, I have a page that I need to verify the user's permission ... The page will only be accessed if the user is an administrator.

When the user accesses the treatment page and is not an ADMINISTRATOR user, the page should not be accessed.

I want to know how to do this in the filter part in Java. My code is this:

    public void doFilter(ServletRequest request, ServletResponse response, 
    FilterChain chain) throws IOException, ServletException {

    String context = request.getServletContext().getContextPath();

    try{
        HttpSession session = ((HttpServletRequest)request).getSession();
        User user = null;
        if(session != null){
            user = (User) session.getAttribute("user");

        }
        if(user == null){
            HttpServletResponse resp =((HttpServletResponse)response);

            resp.sendRedirect(context + "/");
        } else {
            chain.doFilter(request, response);
            JPAUtil.closeEntityManager();
        }
    }catch(Exception e){
        e.printStackTrace();
    }
}
    
asked by anonymous 25.08.2017 / 01:25

1 answer

0

Very simple friend, in the Database, you will have to save the type of a user, administrator, or client. When you put the user in the session, make sure the type is set, in the filter you would do something like:

First you do the filter mapping, in my case, all pages that have "/admin/" will be filtered so that only administrators have access.

The mapping is done this way

@WebFilter(urlPatterns="/admin/*")
public class FilterAdm implements Filter

This is the doFilter method

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;
    User user = (User) req.getSession().getAttribute("userSession");
    if (user == null || !user.getType().equals("adm")) {
        resp.sendError(400);
    } else {
        chain.doFilter(request, response);
    }     
}

I hope I have helped!

    
25.08.2017 / 01:28