Tuesday 20 August 2013

Basic Security - Part 2 - Basic Auth for your Servlet

In our previous article we went over how to implement SSL certifications to our Tomcat7 server using a combination of an unsigned SSL certification, a keystore and enabling a secure port and protocol to be used for HTTPS requests.

The next step is to provide basic authentication for your servlets running on the Tomcat instance. After validating that the server the client is connecting to is the one they actually meant to connect to, we should require them to login before sending encrypted sensitive material to them.

Open up your tomcat-users.xml file and make sure you have a unique login and password created referencing a unique role. (which we did initially in step 1)

<tomcat-users>
   <role rolename="security_role_101"/>
   <role rolename="security_role_something" />
   <user username="UniqueUsernameForSomething"
      password="SuperLongPassword6666"
      roles="valid_mobile_user"/>
   <user username="super_admin_login"
      password="superComplicatedPass6"
      roles="security_role_101"/>
</tomcat-users>

Once a user-connects we are going to make the servlet challenge for username UniqueUsernameForSomething.

To do this, open your project and go to the web.xml file. Generally this is found under the folder WebContent/WEB-INF/

Add the following between the fields.

<security-constraint>
   <web-resource-collection>
      <web-resource-name>App-Name</web-resource-name>
      <url-pattern>/*</url-pattern>
   </web-resource-collection>
   <auth-constraint>
      <role-name>security_role_101</role-name>
   </auth-constraint>
   <user-data-constraint>
      <transport-guarantee>CONFIDENTIAL</transport-guarantee>
   </user-data-constraint>
</security-constraint>

<login-config>
   <auth-method>BASIC</auth-method>

</login-config>

This forces basic auth on any URL route for www.servername.com/* and checks that the passed in username and password is in the role "security_role_101". The transport guarantee of CONFIDENTIAL tells the app to only send the data in a way which ensures the information cannot be changed or observed during transmission.

Compile your war and redeploy. Browse to your test URL of www.servername.com:secureport/mypage and it should now prompt you for your login details.

Enjoy.

No comments:

Post a Comment