Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Security getAuthentication() returns null

I'm trying the return the currently logged in user from my Spring Boot + AngularJS application, but SecurityContextHolder.getContext().getAuthentication() returns null.

Security config:

@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
            .withUser("test").password("test").roles("USER", "ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .formLogin().and()
            .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).and()
            .authorizeRequests()
            .antMatchers("/index.html", "/login.html", "/").permitAll()
            .anyRequest().authenticated().and()
            .addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class)
            .csrf().csrfTokenRepository(csrfTokenRepository());
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/bower_components/**");
        web.ignoring().antMatchers("/js/**");
        web.ignoring().antMatchers("/css/**");
        web.ignoring().antMatchers("/api/user");
    }

    private static CsrfTokenRepository csrfTokenRepository() {
        HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
        repository.setHeaderName("X-XSRF-TOKEN");
        return repository;
    }
}

Controller:

@RequestMapping(value="/user", method = RequestMethod.GET)
@ResponseBody
public User user() {
    User user = new User();
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null) {
        String name = auth.getName();
        user.setUsername(name);
    }
    return user;
}
like image 268
user3170702 Avatar asked Apr 04 '16 20:04

user3170702


2 Answers

Assuming that the controller you show is mapped to the context /api/user, then the reason is because you've added the line web.ignoring().antMatchers("/api/user"); to your security configuration, which means that all requests to that controller are not secured, and thus also don't have a SecurityContext. Remove that line, so that Spring Security secures it.

Excerpt from the Javadoc of the ignoring method:

Web Security provided by Spring Security (including the SecurityContext) will not be available on HttpServletRequest that match.

like image 76
dunni Avatar answered Nov 09 '22 05:11

dunni


Another reason might be you've spun up another thread to the original one requesting the resource. That also happens when doing a parallelStream().foreach.

like image 41
icyerasor Avatar answered Nov 09 '22 05:11

icyerasor