How to implement authentication mechanism in Java EE 6

Zeck picture Zeck · Jun 4, 2010 · Viewed 8.9k times · Source

I'm trying to learn Java EE 6 and i'm just wondering how to implement authentication mechanism in Java EE 6.

Here is the Java EE 6 authentiction example:

    public void login() {
    if (account.authenticate(name, password) == null) {
        message = "Invalid user name or password!";
    } else {
        message = " Login successful";
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
        try {
            request.login(this.name, this.password);
            Principal principal = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
            name = principal.getName();
        } catch (ServletException e) {
            // Handle unknown username/password in request.login().
            context.addMessage(null, new FacesMessage("Unknown login"));
        }
    }
}

I have a following questions:

  1. How request.login function check name and password? It isn't know user entity?
  2. If it isn't right way. How to implement standart authentication mechanism

In finally thank you for your advise and i need a very good tutorials or advise.

Answer

Pascal Thivent picture Pascal Thivent · Jun 4, 2010

How request.login function check name and password? It isn't know user entity?

The request.login allows to implement programmatic security and validates the provided username and password in the password validation realm used by the web container login mechanism configured for the ServletContext.

In other words, it delegates the authentication check to the container and this check is done against the security realm of the webapp. This is a very nice alternative to FORM-based authentication.

Authentication Without the Form has had a nice screencast showing this feature in action. If you don't want to use a file realm but a JDBC realm, check this blog post.

See also