Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve Spring Security's Authentication, even on public pages with filter="none"

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.

like image 393
jtoberon Avatar asked Sep 27 '11 18:09

jtoberon


People also ask

How do I bypass WebSecurityConfigurerAdapter?

Step 1: Add the security jar or dependency in your application. Step 2: Create a security config class and extend the WebSecurityConfigurerAdapter class. Step 3: Add the annotation @EnableWebSecurity on top of the class. Step 4: For authentication, override the method configure(AuthenticationManagerBuilder auth) .

What should I use instead of WebSecurityConfigurerAdapter?

You need to declare SecurityFilterChain and WebSecurityCustomizer beans instead of overriding methods of WebSecurityConfigurerAdapter class.


1 Answers

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").

like image 169
axtavt Avatar answered Nov 15 '22 17:11

axtavt