Accessing user details after logging in with Java EE Form authentication

孤街浪徒 提交于 2019-12-10 10:12:40

问题


I have implemented a Java EE security realm that redirects users to login.jsp if they try and access a protected resource.

  • Say a user wants to go to a protected url - http://mywebapp/shopping_cart which is mapped to ShoppingCartServlet
  • As they are not logged in Glassfish directs them to login.jsp
  • They then enter their username and password and click Login and the information gets POSTed to http://mywebapp/j_security_check
  • If they have entered the correct details they are then redirected to the servlet that handles the url http://mywebapp/shopping_cart

Now I want to pull the user's details 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 makes to http://mywebapp/shopping_cart. So what method is used to access the user's details once they log in?


回答1:


Create a filter which checks if the user is logged in while no associated User object from the database is present in the session. Then, just load that data and put in 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);
    }

    // ...
}


来源:https://stackoverflow.com/questions/14758429/accessing-user-details-after-logging-in-with-java-ee-form-authentication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!