Programmatically control login with Servlet 3.0

后端 未结 2 909
灰色年华
灰色年华 2020-12-14 14:03

I\'ve tested the default security containers in Glassfish 3.0.1 and come to the conclusion that I won\'t spend any more time on that. Instead I want to control the verificat

2条回答
  •  误落风尘
    2020-12-14 14:23

    When you want to utilize request.login(), then you should really have configured a Realm in the container which represents the user database. But you seem to have replaced the Realm by some AuthenticationFacade. In this case, the request.login() is not useful for you.

    You need to just put the user in the session scope and intercept on that. Here's a kickoff example:

    @ManagedBean
    @SessionScoped
    public class UserManager {
    
        @EJB
        private UserService userService;
        private String username;
        private String password;
        private User current;
    
        public String login() {
            current = userService.find(username, password);
    
            if (current == null) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Unknown login, try again"));
                return null;
            } else {
                return "userhome?faces-redirect=true";
            }
        }
    
        public String logout() {
            FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
            return "index?faces-redirect=true";
        }
    
        public boolean isLoggedIn() {
            return current != null;
        }
    
        // Getters/setters (but do NOT provide a setter for current!)
    }
    

    When taking authentication in hands like this, then you definitely need a filter to restrict access. When using container managed security you would typically specify it as of for this. But without it, you've to take it in your hands. It's good to know that JSF managed beans are keyed by their managed bean name in any scope.

    UserManager userManager = ((HttpServletRequest) request).getSession().getAttribute("userManager");
    
    if (userManager == null || !userManager.isLoggedIn()) {
        ((HttpServletResponse) response).sendRedirect("login.xhtml");
    } else {
        chain.doFilter(request, response);
    }
    

    Map the above filter on the desired URL-pattern.


    When you still want to reconsider using container managed authentication, then the following related answers may be useful:

    • Java EE Login Page Problem (and Configuring Realm in Glassfish)
    • Performing user authentication in Java EE / JSF using j_security_check

提交回复
热议问题