Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Both isAnonymous() and isAuthenticated() return false on error page

I have an error page which is displayed when a 404 response status is returned. This page is generated thanks to a template mechanism (I use tiles); In this template, I have a header that contains something like that :

    <sec:authorize access="isAnonymous()">
        blabla
    </sec:authorize>
    <sec:authorize access="isAuthenticated()">
        blibli
    </sec:authorize>

So, depending on if the user is authenticated, it displays blibli or blabla. This code works for all pages that use this template except for my 404 page! It displays nothing!

Any idea??

like image 686
tibo Avatar asked Dec 21 '22 17:12

tibo


2 Answers

I'll bet that problem lies in how you define filter-mapping in web.xml. Most common configuration is:

<filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping>

This maps filter to all URLs, but only when they accessed by REQUEST method. All other cases (like INCLUDE, FORWARD and ERROR) not catched by this filter. So to bind filter to ERROR requests, define it as

<filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>

        <!-- apply Spring Security authentication to error-pages -->
        <dispatcher>ERROR</dispatcher>
</filter-mapping>

Try it. If not works then add <dispatcher>INCLUDE</dispatcher> because Tiles, probably includes pages by this way.

See also:

  • Dispatcher for Filter Mapping

  • Specifying Filter Mappings

like image 184
Slava Semushin Avatar answered Dec 24 '22 01:12

Slava Semushin


For those looking for java configuration:

private void registerSpringSecurityFilterChain(ServletContext servletContext) {
  FilterRegistration.Dynamic springSecurityFilterChain = servletContext.addFilter(
        BeanIds.SPRING_SECURITY_FILTER_CHAIN, new DelegatingFilterProxy());
  springSecurityFilterChain.addMappingForUrlPatterns(null, false, "/*");
  springSecurityFilterChain.addMappingForUrlPatterns(EnumSet.of(DispatcherType.ERROR), false, "/*");

}
like image 32
brad12s Avatar answered Dec 24 '22 03:12

brad12s