abiieez
abiieez

Reputation: 3189

Why Spring Security authentication gives null

I have the following website under my Tomcat (both using Spring MVC)

www.example.com (anyone can access)
www.example.com/member (only authenticated user)

and my method in my HTTPErrorController

@RequestMapping(value = "/errors/404.html")
    public String handle404(HttpServletRequest request, Exception e) {
        logger.error(e.getMessage());
        Authentication authentication = SecurityContextHolder.getContext()
                .getAuthentication();
        return authentication == null ? defaultPage : defaultAuthorizedPage;
        // return defaultAuthorizedPage;
    }

Spring Security

<intercept-url pattern="/*" access="hasAnyRole('ROLE_USER', 'ROLE_ADMIN','ROLE_ANONYMOUS')"
            requires-channel="https" />
<intercept-url pattern="/member/**" access="isFullyAuthenticated()"
            requires-channel="https" />

Now if a user has logged and try to access non-existent page it should be redirected to the www.example.com/member/home (default authorized page) while normal user / guest should be redirected to the home page www.example.com/home (default page).

The issue is the authentication is always null thus I am not able to determine if user has logged. What should I do about this ?

Upvotes: 0

Views: 509

Answers (1)

Rob Winch
Rob Winch

Reputation: 21720

If you want error pages that are managed by the container to be protected / include Spring Security's SecurityContext you need to ensure to include the ERROR request dispatcher for the springSecurityFilterChain. For example the following in your web.xml

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

Upvotes: 1

Related Questions