New Security Features in Glassfish v3 (Java EE 6) - Part II
By nitkal on Dec 24, 2009
The authenticate() method
In continuation of the post on the new security features in Java EE 6 that focused on http-method-omissions, this post aims to elucidate yet another feature in servlet security introduced in Java EE 6 (and implemented in Glassfish v3) - the authenticate() method.
This method is provided in the javax.servlet.http.HttpServletRequest interface. The method signature is as follows:
public boolean authenticate(HttpServletResponse response) throws IOException,ServletException
This method is one of the examples of programmatic security (login, in particular) in Java EE 6. It can be used as an alternative to the <auth-constraint>. When used in a servlet or a JSP, it forces authentication, using the login-mechanism specified in web.xml, even if no security-constraint element is specified in the web.xml.
After a call to authenticate succeeds, the user credentials are validated and the following methods provide the expected results:
(i) getRemoteUser() - the name of the remote user associated with the request,
(ii) isUserInRole() - determines if the remote user (that is, the caller) associated with the request is in a specified security role - returns true after a successful authenticate, provided the role is specified.
(iii) getUserPrincipal() - method determines the principal name of the remote user (that is, the caller) and returns a java.security.Principal object corresponding to the remote user.
The advantage of using the authenticate method is that it provides the flexibility to login in dynamically combined with the ability to be used with the configured login-mechanism like BASIC. Here is a sample application that illustrates the authenticate method. On deploying the war file and accessing the servlet (http://<server-name>:<port-number>/testsam/test , BASIC authentication is forced by the container, since the call to authenticate() is made in the service method of the servlet.