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.
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) .
You need to declare SecurityFilterChain and WebSecurityCustomizer beans instead of overriding methods of WebSecurityConfigurerAdapter class.
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"
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With