How I can authenticate a user from JSF action (or in servlet doGet
/doPost
methods)?
I mean something like:
Authenticator auth = ...;
if (!auth.authenticate("user","password"))
{
FacesContext.getInstance().addMessage("Incorrect username or password", null);
}
Restrictions:
- This method must be compatible with container managed security. (i.e. `HttpServletRequest.getRemoteUser()` must return authenticated user)
- This method must work everywhere (i.e. on each application server).
Not using j_security_check
or another J2EE authentication type (BASIC, DIGEST, etc...)
It is possible?
Or how to create captcha in this way?
Validate that login and password is not empty?
On single page and without JavaScript, of course...
Similar questions... but without answer on this question:
JSF authentication and authorization
Performing user authentication in Java EE / JSF using j_security_check
Edit 1:
I mean serlvet API at least 2.3.
Yes, I read about login
in Servlet API 3.0, but it is supported only by new versions of application servers.
I think that here can be some solution that implements this authentication for each application server. Sometimes via some hacks, sometimes via special classes designed for this purpose. Like this:
private Class<?> tryClass(String name)
{
try
{
return Class.forName(name);
}
catch (ClassNotFoundException e)
{
return null;
}
}
public boolean authenticate(String username, String password) throws AuthenticationException
{
try
{
ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
Object request = context.getRequest();
Object response = context.getResponse();
Class<?> authClass = tryClass("com.sun.appserv.security.ProgrammaticLogin");
if (authClass != null)
{
return (Boolean)authClass.getMethod("login").invoke(
authClass.newInstance(), "user", "password", request, response);
}
authClass = tryClass("org.jboss.web.tomcat.security.login.WebAuthentication");
if (authClass != null)
{
return (Boolean)authClass.getMethod("login").invoke(
authClass.newInstance(), "user", "password");
}
// ... other hacks ...application servers
}
catch (Exception e)
{
throw new AuthenticationException("an error occured during user authentication", e);
}
return false;
}