Search code examples
apachejsfshiro

Apache Shiro doesn't redirect me to login.xhtml in JSF


I'm learning Shiro step-by-step with @BalusC's article, there is no problem until I turning it into form based authentication as the fifth part of the article said.

I did exactly what the article said, but the shiro didn't redirect me to the login page, instead, it always shows index.xhtml whenever I run my web app.

Here's my code, I have no idea what have I missed.

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<listener>
    <listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
</listener>

<filter>
    <filter-name>shiroFilter</filter-name>
    <filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
</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>
<context-param>
    <param-name>javax.faces.PROJECT_STAGE</param-name>
    <param-value>Development</param-value>
</context-param>
<servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<session-config>
    <session-timeout>
        30
    </session-timeout>
</session-config>
<welcome-file-list>
    <welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
</web-app>

shiro.ini:

[main]
authc.loginUrl = /login.xhtml

[users]
admin = password

[urls]
/login.xhtml = authc
/app/** = authc

It should have redirect me to the login.xhtml, shouldn't it?
Any ideas? Thanks in advance.


Solution

  • If the exact url of your index.xhtml that is being used in the browser is /index.xhtml or /faces/index.xhtml (and not /app/index.xhtml/), then it is simply not secured and you need to add an extra line. Also, login.xhtml should not be secured:

    [urls]
    /login.xhtml = anon
    /index.xhtml = authc
    /app/** = authc
    

    Also, if the url your entering in the browser is /, it is not secured at all.

    Shiro looks at the url the browser comes in from, it doesn't know anything about jsf.

    So if it is your goal to protect everything, the config should be:

    [urls]
    /login.xhtml = anon
    /** = authc
    

    Note that the order matters, the first hit is where it will react to. So the login should come first and then everything else, otherwise your login page will be secured as well.