I was doing a simple servlet based web application that should on WebSphere Application Server 8.5.5.6 the other day. The servlet should require authentication. I really wanted to avoid using web.xml and go annotation based but it turned out that it wasn’t possible – at least for me. Servlets are secured using the @ServletSecurity and you specify required role(s) and HTTP constraints e.g. is HTTPS required etc.
I added the following annotations:
@WebServlet(urlPatterns={"/"}, initParams={@WebInitParam(name="foo", value="bar")})
@ServletSecurity(@HttpConstraint(rolesAllowed={"users"}))
The “users” role turned up just fine in WAS ISC but I couldn’t make the authentication kick in when I accessed the resources. Changing settings and values for the @ServletSecurity annotation e.g. explicitly mentioning GET didn’t do anything for me. For some reason the annotation wasn’t enough. To make the authentication kick in I had to add the following web.xml which is pretty much a standard web.xml you would do without annotations. You might be able to get away with a little less but at least I got it working… Oh well…
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="xmlns.jcp.org/xml/ns/javaee" xmlns:jsp="http://java.sun.com/xml/ns/javaee/jsp"
xmlns:web="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="xmlns.jcp.org/xml/ns/javaee xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd
http://xmlns.jcp.org/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="3.1">
<display-name>MyApp</display-name>
<security-constraint>
<web-resource-collection>
<web-resource-name>Protected Area</web-resource-name>
<url-pattern>/*</url-pattern>
<http-method>GET</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>users</role-name>
</auth-constraint>
</security-constraint>
<security-role>
<role-name>users</role-name>
</security-role>
<login-config>
<auth-method>BASIC</auth-method>
</login-config>
</web-app>
