Issue
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;
}
Solution
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.
Answered By - dunni
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.