Get Spring Security Authentication, even on public pages with filter = "none"

Say I have a simple faq.html page. I want this page to be publicly available, so I am applying the usual Spring security configuration:

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

Suppose also that if the user reaches this page after authentication, I want to print "Hi Firstname Lastname" on the page. For pages requiring authentication, I just put the result of the following into my ModelMap , and then the names are available in my view later:

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

This does not work for faq.html , apparently because when you specify filters="none" , the call to getPrincipal() returns null. (This behavior makes sense, since filters are not applied in the configuration). So instead, it seems to me that I should manually create a Spring Security bunch:

 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 that Spring should provide some ability to connect its API calls through the original <sec:intercept-url /> configuration.

+8
java spring-security
source share
1 answer

In order 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 do not have use-expressions = "true" ).

+11
source share

All Articles