8

Let's say I have a simple page called faq.html. I want this page to be publicly accessible, so I apply the usual Spring Security configuration:

<sec:intercept-url pattern="/faq.html" filters="none" />

Let's also say that if the user reaches this page after authenticating, I want to print "Hi Firstname Lastname" on the page. For pages that require authentication, I simply put the result of the following into my ModelMap, and then the names are accessible in my view later:

SecurityContextHolder.getContext().getAuthentication().getPrincipal()

This doesn't work for faq.html, presumably because when you specify filters="none", then the call to getPrincipal() returns null. (This behavior makes sense since the configuration causes no filters to be applied.) So, instead it seems that I have to do a bunch of the Spring Security stuff manually:

public static Authentication authenticate(HttpServletRequest request,
        HttpServletResponse response, SecurityContextRepository repo,
        RememberMeServices rememberMeServices) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    // try to load a previous Authentication from the repository
    if (auth == null) {
        SecurityContext context = repo.loadContext(
                new HttpRequestResponseHolder(request, response));
        auth = context.getAuthentication();
    }

    // check for remember-me token
    if (auth == null) {
        auth = rememberMeServices.autoLogin(request, response);
    }

    return auth;
}

Is there a better way to do this? For example, it seems like Spring should provide some facility for hooking their API calls in via the original <sec:intercept-url /> config.

jtoberon
  • 8,706
  • 1
  • 35
  • 48
  • Note that `filters="none"` seems to have been deprecated in Spring 3.1.0: http://stackoverflow.com/a/5382178/521799 – Lukas Eder Oct 09 '12 at 12:04

1 Answers1

11

That's the reason not to use filters = "none" for public pages.

Use access = "permitAll" instead (or access = "IS_AUTHENTICATED_ANONYMOUSLY, IS_AUTHENTICATED_FULLY, IS_AUTHENTICATED_REMEMBERED" if you don't have use-expressions = "true").

axtavt
  • 239,438
  • 41
  • 511
  • 482