2016-04-04 31 views
2

Şu anda oturum açmış olan kullanıcı Spring Boot + AngularJS uygulamasından döndürmeyi deniyorum, ancak SecurityContextHolder.getContext().getAuthentication() döndürüyor.Spring Security getAuthentication() null değerini döndürür

Güvenlik yapılandırma:

@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; 
    } 
} 

Denetleyici: Eğer hattı web.ignoring().antMatchers("/api/user"); ekledik çünkü

@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; 
} 

cevap

3

göstermek denetleyici çerçevede /api/user eşleştirilmiş varsayarsak, o zaman neden senin Güvenlik yapılandırması, yani bu denetleyiciye yapılan tüm isteklerin güvenceye alınmadığı ve bu nedenle de bir SecurityContext bulunmadığı anlamına gelir. Bu çizgiyi kaldırın, böylece Spring Security onu korur. görmezden yöntemin Javadoc gelen

alıntı: (SecurityContext dahil) Bahar Security tarafından sağlanan

Web Security HttpServletRequest o maç kullanılamaz.

+0

Harika, çok teşekkürler. – user3170702

İlgili konular