Search code examples
javaweb-servicesrestshiro

Using a Shiro Filter on JAX-RS without Web.xml


I am using JAX-RS and I have a rest service that I would like to secure using shiro basic auth. I currently have a class that extends Application as per the Servlet 3 spec and everything run fine. I can't seem to get Shiro basic auth filter to work and since I have no web.xml, it will not let me add a filter chain there. Is there a way to programatically add a filter in my application sub class?


Solution

  • You could add a web descriptor to your application. According to Servlet 3.0 specs, web.xml is optional and just extends and/or overrides your annotation configuration.

    You could then define a Shiro filter in your web.xml as usual and JAX-RS related configuration will stay configured via annotations. This is a natural approach.

    <filter>
        <filter-name>ShiroFilter</filter-name>
        <filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
        <init-param>
            <param-name>configPath</param-name>
            <param-value>classpath:shiro.ini</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>ShiroFilter</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
        <dispatcher>INCLUDE</dispatcher>
        <dispatcher>ERROR</dispatcher>
    </filter-mapping>
    

    If it is not an option for you and you don't want web.xml to arise in your application, you could also extend from ShiroFilter class and provide your own annotation configurations in order to get Shiro filter chained:

    @WebFilter(initParams = { @WebInitParam(name = "configPath", value = "classpath:shiro.ini") })
    public class MyShiroFilter extends ShiroFilter {
    }
    

    I didn't test that code above, this is just an approach.