25 May 2009

JSP/servlet authentication

You can define authentication in the web.xml deployment descriptor of a web application.

  1. Define roles
    <security-role>   
      <role-name>admin</role-name>    
    </security-role>    
    <security-role>    
      <role-name>boss</role-name>    
    </security-role>
    User definition is web container dependent. 
  2. Define protected resources
    <security-constraint>   
      <display-name>Goodies</display-name>    
      <web-resource-collection>    
        <web-resource-name>Goodies</web-resource-name>    
        <description/>    
        <url-pattern>/Cookies</url-pattern>    
        <url-pattern>/Smarties/*</url-pattern>    
      </web-resource-collection>    
      <auth-constraint>    
        <description/>    
        <role-name>admin</role-name>    
        <role-name>boss</role-name>    
      </auth-constraint>    
    </security-constraint>
    Take care:
    • Is only guaranteed for cookie based sessions
    • Does not apply to forward and include
  3. Define authentication method
    <login-config>   
      <auth-method>FORM</auth-method>    
      <realm-name/>    
      <form-login-config>    
        <form-login-page>/login.jsp</form-login-page>    
        <form-error-page>/login-error.jsp</form-error-page>    
      </form-login-config>    
    </login-config>
    The authentication form is supposed to have a POST action called j_security_check and j_username and j_password input fields.
    Other HTTP authentication methods are
    • BASIC: clear text password (base64 encoded)
    • DIGEST: hashed password (works in Firefox and IE 7+)
    • CLIENT-CERT: mutual certified SSL