Ich versuche, den aktuell angemeldeten Benutzer von meiner Spring Boot + AngularJS-Anwendung zurückgeben, aber SecurityContextHolder.getContext().getAuthentication()
gibt null zurück.Spring Security getAuthentication() gibt null zurück
Sicherheits 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;
}
Großartig, vielen Dank. – user3170702