Blocking direct URL access in JSF web application

1.4k Views Asked by At

In my project, I want to restrict direct URL access in my JSF web application. Although I found it on the web that give suggestions to configure security constraints in web.xml.

   <security-constraint>
    <display-name>Restrict raw XHTML Documents</display-name>
    <web-resource-collection>
        <web-resource-name>XHTML</web-resource-name>
        <url-pattern>/manage/*</url-pattern>
        <http-method>GET</http-method>
        <http-method>POST</http-method>
    </web-resource-collection>
    <auth-constraint />
    <user-data-constraint>
        <transport-guarantee>NONE</transport-guarantee>
    </user-data-constraint>
</security-constraint>

So that, I can restrict direct URL access to /manage/*.jsp. But I have many folders to restrict such as /view/*.jsp, /others/*.jsp, etc. And I want to show error page when occur.

2

There are 2 best solutions below

2
On

one way would be to move the jsp files inside the web-inf directory which will block direct url accesss

0
On

You probably would have figured out the solution by now but thought of answering it.

Way to achieve the restriction is by having all the url-patterns as part of web-resource-collection. And you can define one another security-constraint without auth-constraint to allow direct access like below.

    <security-constraint>
        <display-name>Restrict raw XHTML Documents</display-name>
        <web-resource-collection>
            <web-resource-name>XHTML</web-resource-name>
            <url-pattern>/manage/*</url-pattern>
            <url-pattern>/view/*</url-pattern>
            <http-method>GET</http-method>
            <http-method>POST</http-method>
        </web-resource-collection>
        <auth-constraint />
        <user-data-constraint>
            <transport-guarantee>NONE</transport-guarantee>
        </user-data-constraint>
    </security-constraint>

<security-constraint>
    <display-name>Allow login pages</display-name>
    <web-resource-collection>
        <web-resource-name>Seam</web-resource-name>
        <url-pattern>*.seam</url-pattern>
        ...<!-- You can define all the url-patterns you want to allow direct access to -->

    </web-resource-collection>

</security-constraint>

You are using empty auth-constraint which means regardless of authentication, it blocks direct access to all the URL patterns listed. You will get 403 error and you can define a page for it with error page tag

<error-page>
    <error-code>403</error-code>
    <location>/path/to/error.jsp</location>
    </error-page>

Otherwise, you can use error-page tags to define error jsps.

<error-page>
<exception-type>anyexception class name</exception-type>
<location>/path/to/error.jsp</location>
</error-page>