user1935987 user1935987 - 1 month ago 55
Java Question

Spring Boot Security Anonymous authorization

For multiple purposes I need to use

SecurityContextHolder.getContext().getAuthentication()


methods in my controllers/services.

I did migrate my app to Spring Boot 1.4.1 from XML configured Spring MVC app (now only Java configs), similar approach worked before.

I have a problem calling
SecurityContextHolder.getContext().getAuthentication()
, for example in this controller:

@RestController
@Secured("IS_AUTHENTICATED_ANONYMOUSLY")
@RequestMapping("utils")
public class UtilsController {
@RequestMapping(value = "/check_auth", method = RequestMethod.GET)
public Boolean getAuthState() throws SQLException {
if (SecurityContextHolder.getContext().getAuthentication() == null){
logger.info("Auth obj null");
}

if (SecurityContextHolder.getContext().getAuthentication().getName() != null && SecurityContextHolder.getContext().getAuthentication().getName() != "anonymousUser") {
return true;
} else return false;
}
}


it always returns
null
. Can't figure out why anonymous authentication is not working.

Here is the Spring Security configuration:

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint).and()
.formLogin()
.successHandler(ajaxSuccessHandler)
.failureHandler(ajaxFailureHandler)
.loginProcessingUrl("/authentication")
.passwordParameter("password")
.usernameParameter("username")
.and()
.logout()
.deleteCookies("JSESSIONID")
.invalidateHttpSession(true)
.logoutUrl("/logout")
.logoutSuccessUrl("/")
.and()
.csrf().disable()
// .anonymous().disable()
.authorizeRequests()
// .anyRequest().anonymous()
.antMatchers("/utils").permitAll()
.antMatchers("/oauth/token").permitAll()
.antMatchers("/admin/*").access("hasRole('ROLE_ADMIN')")
.antMatchers("/user/*").access("hasRole('ROLE_USER')");
}


I did tried with and without
@Secured
annotation on the controller.

.authorizeRequests()
// .anyRequest().anonymous()
.antMatchers("/utils").permitAll()


different variations with this settings.

Answer

You are getting null with:

SecurityContextHolder.getContext().getAuthentication()

because you are not authenticating within you security configuration.

You can add a simple:

.authenticated()                                                 
            .and()
        // ...
        .formLogin();

in case you're using form login.

Now after you'll authenticate each request you suppose to get something other than null.

Here's an example from Spring Security docs:

protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()                                                                
            .antMatchers("/resources/**", "/signup", "/about").permitAll()                  
            .antMatchers("/admin/**").hasRole("ADMIN")                                      
            .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")            
            .anyRequest().authenticated()                                                   
            .and()
        // ...
        .formLogin();
}