While configuring the security constraints for a web-module's roles in J2EE application I'm having the following problem:
Application:
Giving a servlet named customersServlet, which receives two parameters in the URL:
A string representing an operation (INS, UPD, DLT and DSP).
An identification number to identify a customer on which the operation will be performed.
E.G.: the url /servlet/cusotmersServlet?UPD,5 is used to update customer number 5 data, and the url /servlet/customersServlet?DLT,8 is used to delete customer number 8.
Problem:
If I use this security-constraint the servlet can only be accessed by the role specified, which is ok:
<security-constraint>
<web-resource-collection>
<web-resource-name>...</web-resource-name>
<url-pattern>/servlet/clientsServlet*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>clientAdmin</role-name>
</auth-constraint>
</security-constraint>
But I want to restrict the ability to insert customers only to a role named clientAdmin.
I've tried several url patterns but none of them works as I want (all of them allow every role to access the servlet with any parameter):
<url-pattern>/servlet/clientsServlet?INS,*</url-pattern>
<url-pattern>/servlet/clientsServlet?INS/*</url-pattern>
...
How to use the wildcard * in the url-pattern tag?
Note: The application cannot be changed, so I need a solution that only implies touching the deployment descriptor.
The <url-pattern> tag only allows a very restricted subset of wildcards. This is probably not what you are used to from other situations, where a * can be used at any position. You can download the Servlet specification here:
http://jcp.org/aboutJava/communityprocess/mrel/jsr154/index2.html
Section SRV.11.2 of that document describes how these URL patterns are interpreted. In particular, the * does not mean "zero or more arbitrary characters" here.
Note: The application cannot be changed, so I need a solution that only implies touching the deployment descriptor.
Not sure if this counts as an application change - perhaps you could think of it as a plug-in. You could add a Filter. This would require the ability to add a new JAR to WEB-INF/libs and the ability to define the filter in web.xml. The Filter would allow you to restrict access programmatically.
Related
The familiar code:
<servlet-mapping>
<servlet-name>main</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>main</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
My understanding is that /* maps to http://host:port/context/*.
How about /? It sure doesn't map to http://host:port/context root only. In fact, it will accept http://host:port/context/hello, but reject http://host:port/context/hello.jsp.
Can anyone explain how is http://host:port/context/hello mapped?
<url-pattern>/*</url-pattern>
The /* on a servlet overrides all other servlets, including all servlets provided by the servletcontainer such as the default servlet and the JSP servlet. Whatever request you fire, it will end up in that servlet. This is thus a bad URL pattern for servlets. Usually, you'd like to use /* on a Filter only. It is able to let the request continue to any of the servlets listening on a more specific URL pattern by calling FilterChain#doFilter().
<url-pattern>/</url-pattern>
The / doesn't override any other servlet. It only replaces the servletcontainer's built in default servlet for all requests which doesn't match any other registered servlet. This is normally only invoked on static resources (CSS/JS/image/etc) and directory listings. The servletcontainer's built in default servlet is also capable of dealing with HTTP cache requests, media (audio/video) streaming and file download resumes. Usually, you don't want to override the default servlet as you would otherwise have to take care of all its tasks, which is not exactly trivial (JSF utility library OmniFaces has an open source example). This is thus also a bad URL pattern for servlets. As to why JSP pages doesn't hit this servlet, it's because the servletcontainer's built in JSP servlet will be invoked, which is already by default mapped on the more specific URL pattern *.jsp.
<url-pattern></url-pattern>
Then there's also the empty string URL pattern . This will be invoked when the context root is requested. This is different from the <welcome-file> approach that it isn't invoked when any subfolder is requested. This is most likely the URL pattern you're actually looking for in case you want a "home page servlet". I only have to admit that I'd intuitively expect the empty string URL pattern and the slash URL pattern / be defined exactly the other way round, so I can understand that a lot of starters got confused on this. But it is what it is.
Front Controller
In case you actually intend to have a front controller servlet, then you'd best map it on a more specific URL pattern like *.html, *.do, /pages/*, /app/*, etc. You can hide away the front controller URL pattern and cover static resources on a common URL pattern like /resources/*, /static/*, etc with help of a servlet filter. See also How to prevent static resources from being handled by front controller servlet which is mapped on /*. Noted should be that Spring MVC has a built in static resource servlet, so that's why you could map its front controller on / if you configure a common URL pattern for static resources in Spring. See also How to handle static content in Spring MVC?
I'd like to supplement BalusC's answer with the mapping rules and an example.
Mapping rules from Servlet 2.5 specification:
Map exact URL
Map wildcard paths
Map extensions
Map to the default servlet
In our example, there're three servlets. / is the default servlet installed by us. Tomcat installs two servlets to serve jsp and jspx. So to map http://host:port/context/hello
No exact URL servlets installed, next.
No wildcard paths servlets installed, next.
Doesn't match any extensions, next.
Map to the default servlet, return.
To map http://host:port/context/hello.jsp
No exact URL servlets installed, next.
No wildcard paths servlets installed, next.
Found extension servlet, return.
Perhaps you need to know how urls are mapped too, since I suffered 404 for hours. There are two kinds of handlers handling requests. BeanNameUrlHandlerMapping and SimpleUrlHandlerMapping. When we defined a servlet-mapping, we are using SimpleUrlHandlerMapping. One thing we need to know is these two handlers share a common property called alwaysUseFullPath which defaults to false.
false here means Spring will not use the full path to mapp a url to a controller. What does it mean? It means when you define a servlet-mapping:
<servlet-mapping>
<servlet-name>viewServlet</servlet-name>
<url-pattern>/perfix/*</url-pattern>
</servlet-mapping>
the handler will actually use the * part to find the controller. For example, the following controller will face a 404 error when you request it using /perfix/api/feature/doSomething
#Controller()
#RequestMapping("/perfix/api/feature")
public class MyController {
#RequestMapping(value = "/doSomething", method = RequestMethod.GET)
#ResponseBody
public String doSomething(HttpServletRequest request) {
....
}
}
It is a perfect match, right? But why 404. As mentioned before, default value of alwaysUseFullPath is false, which means in your request, only /api/feature/doSomething is used to find a corresponding Controller, but there is no Controller cares about that path. You need to either change your url to /perfix/perfix/api/feature/doSomething or remove perfix from MyController base #RequestingMapping.
I think Candy's answer is mostly correct. There is one small part I think otherwise.
To map host:port/context/hello.jsp
No exact URL servlets installed, next.
Found wildcard paths servlets, return.
I believe that why "/*" does not match host:port/context/hello because it treats "/hello" as a path instead of a file (since it does not have an extension).
The essential difference between /* and / is that a servlet with mapping /* will be selected before any servlet with an extension mapping (like *.html), while a servlet with mapping / will be selected only after extension mappings are considered (and will be used for any request which doesn't match anything else---it is the "default servlet").
In particular, a /* mapping will always be selected before a / mapping. Having either prevents any requests from reaching the container's own default servlet.
Either will be selected only after servlet mappings which are exact matches (like /foo/bar) and those which are path mappings longer than /* (like /foo/*). Note that the empty string mapping is an exact match for the context root (http://host:port/context/).
See Chapter 12 of the Java Servlet Specification, available in version 3.1 at http://download.oracle.com/otndocs/jcp/servlet-3_1-fr-eval-spec/index.html.
The familiar code:
<servlet-mapping>
<servlet-name>main</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>main</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
My understanding is that /* maps to http://host:port/context/*.
How about /? It sure doesn't map to http://host:port/context root only. In fact, it will accept http://host:port/context/hello, but reject http://host:port/context/hello.jsp.
Can anyone explain how is http://host:port/context/hello mapped?
<url-pattern>/*</url-pattern>
The /* on a servlet overrides all other servlets, including all servlets provided by the servletcontainer such as the default servlet and the JSP servlet. Whatever request you fire, it will end up in that servlet. This is thus a bad URL pattern for servlets. Usually, you'd like to use /* on a Filter only. It is able to let the request continue to any of the servlets listening on a more specific URL pattern by calling FilterChain#doFilter().
<url-pattern>/</url-pattern>
The / doesn't override any other servlet. It only replaces the servletcontainer's built in default servlet for all requests which doesn't match any other registered servlet. This is normally only invoked on static resources (CSS/JS/image/etc) and directory listings. The servletcontainer's built in default servlet is also capable of dealing with HTTP cache requests, media (audio/video) streaming and file download resumes. Usually, you don't want to override the default servlet as you would otherwise have to take care of all its tasks, which is not exactly trivial (JSF utility library OmniFaces has an open source example). This is thus also a bad URL pattern for servlets. As to why JSP pages doesn't hit this servlet, it's because the servletcontainer's built in JSP servlet will be invoked, which is already by default mapped on the more specific URL pattern *.jsp.
<url-pattern></url-pattern>
Then there's also the empty string URL pattern . This will be invoked when the context root is requested. This is different from the <welcome-file> approach that it isn't invoked when any subfolder is requested. This is most likely the URL pattern you're actually looking for in case you want a "home page servlet". I only have to admit that I'd intuitively expect the empty string URL pattern and the slash URL pattern / be defined exactly the other way round, so I can understand that a lot of starters got confused on this. But it is what it is.
Front Controller
In case you actually intend to have a front controller servlet, then you'd best map it on a more specific URL pattern like *.html, *.do, /pages/*, /app/*, etc. You can hide away the front controller URL pattern and cover static resources on a common URL pattern like /resources/*, /static/*, etc with help of a servlet filter. See also How to prevent static resources from being handled by front controller servlet which is mapped on /*. Noted should be that Spring MVC has a built in static resource servlet, so that's why you could map its front controller on / if you configure a common URL pattern for static resources in Spring. See also How to handle static content in Spring MVC?
I'd like to supplement BalusC's answer with the mapping rules and an example.
Mapping rules from Servlet 2.5 specification:
Map exact URL
Map wildcard paths
Map extensions
Map to the default servlet
In our example, there're three servlets. / is the default servlet installed by us. Tomcat installs two servlets to serve jsp and jspx. So to map http://host:port/context/hello
No exact URL servlets installed, next.
No wildcard paths servlets installed, next.
Doesn't match any extensions, next.
Map to the default servlet, return.
To map http://host:port/context/hello.jsp
No exact URL servlets installed, next.
No wildcard paths servlets installed, next.
Found extension servlet, return.
Perhaps you need to know how urls are mapped too, since I suffered 404 for hours. There are two kinds of handlers handling requests. BeanNameUrlHandlerMapping and SimpleUrlHandlerMapping. When we defined a servlet-mapping, we are using SimpleUrlHandlerMapping. One thing we need to know is these two handlers share a common property called alwaysUseFullPath which defaults to false.
false here means Spring will not use the full path to mapp a url to a controller. What does it mean? It means when you define a servlet-mapping:
<servlet-mapping>
<servlet-name>viewServlet</servlet-name>
<url-pattern>/perfix/*</url-pattern>
</servlet-mapping>
the handler will actually use the * part to find the controller. For example, the following controller will face a 404 error when you request it using /perfix/api/feature/doSomething
#Controller()
#RequestMapping("/perfix/api/feature")
public class MyController {
#RequestMapping(value = "/doSomething", method = RequestMethod.GET)
#ResponseBody
public String doSomething(HttpServletRequest request) {
....
}
}
It is a perfect match, right? But why 404. As mentioned before, default value of alwaysUseFullPath is false, which means in your request, only /api/feature/doSomething is used to find a corresponding Controller, but there is no Controller cares about that path. You need to either change your url to /perfix/perfix/api/feature/doSomething or remove perfix from MyController base #RequestingMapping.
I think Candy's answer is mostly correct. There is one small part I think otherwise.
To map host:port/context/hello.jsp
No exact URL servlets installed, next.
Found wildcard paths servlets, return.
I believe that why "/*" does not match host:port/context/hello because it treats "/hello" as a path instead of a file (since it does not have an extension).
The essential difference between /* and / is that a servlet with mapping /* will be selected before any servlet with an extension mapping (like *.html), while a servlet with mapping / will be selected only after extension mappings are considered (and will be used for any request which doesn't match anything else---it is the "default servlet").
In particular, a /* mapping will always be selected before a / mapping. Having either prevents any requests from reaching the container's own default servlet.
Either will be selected only after servlet mappings which are exact matches (like /foo/bar) and those which are path mappings longer than /* (like /foo/*). Note that the empty string mapping is an exact match for the context root (http://host:port/context/).
See Chapter 12 of the Java Servlet Specification, available in version 3.1 at http://download.oracle.com/otndocs/jcp/servlet-3_1-fr-eval-spec/index.html.
A "/" when comes to servlet mapping means default servlet.
How do you interpret this when comes to a URL pattern embedded inside a web-resource-collection element as below:
<security-constraint>
<web-resource-collection>
<web-resource-name>fixmyhome</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>*</role-name>
</auth-constraint>
<user-data-constraint>
<transport-guarantee>NONE</transport-guarantee>
</user-data-constraint>
</security-constraint>
What about "/*'? This URL pattern is not a servlet mapping since it's enclosed by tag web-resource-collection.
I also noticed using http://localhost:8081/fixmyhome/main.jsp using both URL pattern "/" and "/*" gives the same results- which is it gives me the main.jsp page. I thought "/" might not work since there's no wildcard.
The <url-pattern> is looking for an Ant pattern. The patterns available are ?, *, and **; which match 1 character, 0 or more characters, and 0 or more directories respectively.
In your case of http://localhost:8081/fixmyhome/main.jsp, both / and /* are working the same because the * is not a requirement for their to be a character.
If you have a resources directory in your root, I would imagine your <url-pattern> would looks something like this:
<url-pattern>/resources/**</url-pattern>, thereby allowing you access to all sub-directories of the resources directory.
This may help provide some more clarity:
https://ant.apache.org/manual/dirtasks.html
According to this I would say that by writing / you are restricting access to the servlet while by writing /* you are restricting access to a certain path. So essentially "/" and "/*" would be the same.
The url pattern under security constraint does not belong to any mapping for servlet instead it is a regular expression. With the security constraint you can allow/restrict users with the mentioned role (in auth-constraint) for the given URL pattern.
Section 12.2 of servlet specification (version 3) states following:
A string beginning with a ‘/’ character and ending with a ‘/*’ suffix is used for path mapping.
A string beginning with a ‘*.’ prefix is used as an extension mapping.
The empty string ("") is a special URL pattern that exactly maps to the application's context root, i.e.,requests of the form
http://host:port/contextroot/. In this case the path info is ’/’ and
the servlet path and context path is empty string (““).
A string containing only the ’/’ character indicates the "default" servlet of the application. In this case the servlet path
is the request URI minus the context path and the path info is null.
All other strings are used for exact matches only
I am trying to implement a servlet that gets raw requests, and decide either to process them, or forward them to another backend server. It is similar to a load-balancer, where a received request is forwarded to one of the (in my case 2) destinations. One of the destination is remote (on another host). Furthermore, the requests could come to the root (http://mycompany.com/).
Since I want to get raw requests, I implemented my own servlet (subclassing HttpServlet), and that works great. My servlet looks like:
public class MyProxyServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
processOrForward(req, resp);
}
// also doGet(), doHead(), ...
}
Since the service I want to process may send requests to the root, I would like to map my servlet to be the default servlet, thereby receiving any request that does not have an explicit servlet mapping. Assume my servlet's name is "myservlet", and is running along side of another servlet "foo", I expect all requests in the form of http://mycompany.com/foo/... to be delivered to foo, and everything else (e.g., /, /bar/..., /myservlet/...) to "myservlet". Looking at earlier posts (eg., root mapping here and here, or url rewriting here), I thought I figured it out, but it does not work.
Here is my web.xml:
<web-app>
<servlet>
<servlet-name>ProxyServlet</servlet-name>
<servlet-class>com.mycompany.MyProxyServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ProxyServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
In the above web.xml, for url-pattern I tried
"/" and "/*" and empty (i.e., <url-pattern></url-pattern>), all behave the same -->
Requests to root (/)goes to tomcat's default servlet
Requests to /myservlet/... are handled by "myservlet"
Requests to /fubar/... are always 404
Is there a way of turning my servlet to be the default. I.e., any request that does not map specifically to a servlet comes to mine (it is even acceptable to receive all requests, since I can deploy this servlet in its own container). In case it matters, I am using Tomcat 7.0.30 on Ubuntu 12.10.
This should be useful to you.
From the Java™ Servlet Specification Version 3.1 (JSR 340)
Chapter 12. Mapping Requests to Servlets
12.2 Specification of Mappings
In the Web application deployment descriptor, the following syntax is used to define mappings:
A string beginning with a / character and ending with a /* suffix is used for
path mapping.
A string beginning with a *. prefix is used as an extension mapping.
The empty string ("") is a special URL pattern that exactly maps to the
application's context root, i.e., requests of the form http://host:port/<contextroot>/.
In this case the path info is / and the servlet path and context path is
empty string ("").
A string containing only the / character indicates the "default" servlet of the
application. In this case the servlet path is the request URI minus the context path
and the path info is null.
All other strings are used for exact matches only.
As an addition, read this nice explanation with short examples from the book Head First Servlets & JSP: Passing the Sun Certified Web Component Developer Exam (2nd edition) (quote):
The THREE types of <url-pattern> elements
1) EXACT match
Example:
<url-pattern>/Beer/SelectBeer.do</url-pattern>
MUST begin with a slash (/).
Can have an extension (like .do), but it’s not required.
2) DIRECTORY match
Example:
<url-pattern>/Beer/*</url-pattern>
MUST begin with a slash (/).
Always ends with a slash/asterisk (/*).
3) EXTENSION match
Example:
<url-pattern>*.do</url-pattern>
MUST begin with an asterisk (*) (NEVER with a slash).
After the asterisk, it MUST have a dot extension (.do, .jsp, etc.).
IMPORTANT NOTE:
The URL patterns represent logical / virtual structure, i.e. the patterns (paths) specified does not need to exist physically.
UPDATE
If you want, as you say in your comment,
I want host:port to hit my servlet, not the default tomcat servlet
then see the solution here:
How do I make my web application be the Tomcat default application
In other words, what you want is a path without application context, which implies the application context of the Tomcat default application.
Quote from the above link:
In a standard Tomcat installation, you will notice that under the same
directory (CATALINA_BASE)/webapps/, there is a directory called ROOT
(the capitals are important, even under Windows). That is the
residence of the current Tomcat default application, the one that is
called right now when a user calls up
http://myhost.company.com[:port]. The trick is to put your
application in its place.
I am not sure did I understood what you want but probably intercept 404 is what you want to do, then redirect where you want.
I've came here to forum because I have strange problem with tomcat 7, mine is doing just what you want ;)
This is only one way how I can have root, EMPTY
<servlet-mapping>
<servlet-name>Default</servlet-name>
<url-pattern></url-pattern>
</servlet-mapping>
That way : anything is redirected to this servlet, including images, etc, for example, I open another page, this show this one, root, then I can see in log 4 more request to same page, 3 for css and one for image.
<servlet-mapping>
<servlet-name>Default</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
I am quite desperate, because I think there must be an easy solution to my problem but I am searching - to no avail.
I am using a custom Realm in Glassfish 3.1.1. This custom realm (implements AppservPasswordLoginModuleInterface) takes a security token from the HTTPS request, validates the security token and then returns the user to Glassfish.
The problem is that the security token does not contain any groups, meaning that the method public String[] getGroupsList() or the custom realm returns an empty list (correctly, because there are no roles in the security token).
That said, I would like to have a security contraint that only validated users can login. I know that I can use the following constraint in web.xml:
<security-constraint>
<web-resource-collection>
<web-resource-name>mywebapp</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>Users</role-name>
</auth-constraint>
</security-constraint>
But because I don't have any groups, I cannot map any groups to roles, and therefore I cannot use the auth-constraint with role-name.
Is there a way in web.xml to define that only authenticated users are allowed, ignoring in which role they are and ignoring whether they are in any role at all.
There are a couple of solutions which I cannot implement:
I cannot change the underlying LDAP to include roles, because the LDAP schema and the way how LDAP users are mapped to security tokens our out of scope.
I have to use the current custom realm handler, I cannot replace it with one of my own which just returns a default group. I did try this once, and it worked. But I cannot replace the existing custom realm with my own because the custom realm should be generic.
But I really think there should be a way in web.xml just to say: Ignore all groups and roles, I just want an authenticated user?
Any help would be appreciated.
Pretty old, but for those looking for an answer, you can use an * role name:
<auth-constraint>
<role-name>*</role-name>
</auth-constraint>
This guy managed to solve it.
Use two asterisks:
<auth-constraint>
<role-name>**</role-name>
</auth-constraint>
See section 13.8 of the Servlet 4.0 spec: https://javaee.github.io/servlet-spec/downloads/servlet-4.0/servlet-4_0_FINAL.pdf
The single asterisk means a user must have at least one of any declared role vs double asterisks means a user simply must be authenticated. So with single asterisk a user must have one of the roles declared in the security-role section of the web.xml, and it appears some application servers (like JBoss/Wildfly) allow you to also put a single asterisk in this section to make this work similarly to the double asterisks. This single asterisk in the security-role section appears to be non-standard and likely non-portable:
<security-role>
<role-name>*</role-name>
</security-role>