Accessing user data after login using Java EE authentication

I have implemented a Java EE security scope that redirects users to login.jsp if they try to access a secured resource.

  • Suppose the user wants to go to a secure url - http://mywebapp/shopping_cart

    which maps to the ShoppingCartServlet
  • Since they are not logged into Glassfish, they direct them to login.jsp
  • Then they enter their username and password and click "Login" and the information gets a "POSTED" message to http://mywebapp/j_security_check

  • If they entered the correct details, they are then redirected to the servlet that processes the URL http://mywebapp/shopping_cart

Now I want to pull the user data from the database, but how can I when there are no parameters in the redirect request?

Their username was sent to http://mywebapp/j_security_check

, but there are no parameters in the redirect request that j_security_check does with http://mywebapp/shopping_cart

. So what method is used to access user details after login?

+3


source to share


1 answer


Create a filter that checks if the user is logged in while there is no object associated with it in the session User

. Then just load this data and enter the session.

Basically,



@WebFilter("/*")
public class UserFilter implements Filter {

    @EJB
    private UserService service;

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        String remoteUser = request.getRemoteUser();

        if (remoteUser != null) {
            HttpSession session = request.getSession();

            if (session.getAttribute("user") == null) {
                User user = service.find(remoteUser);
                session.setAttribute("user", user);
            }
        }

        chain.doFilter(req, res);
    }

    // ...
}

      

+4


source







All Articles