2016-04-04 5 views
2

私はSpring Boot + AngularJSアプリケーションから現在ログインしているユーザーを返そうとしていますが、SecurityContextHolder.getContext().getAuthentication()はnullを返します。Spring Security getAuthentication()はnullを返します

セキュリティ設定:

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

コントローラ:あなたに行web.ignoring().antMatchers("/api/user");を追加しましたので、

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

答えて

3

はあなたが表示され、コントローラは、コンテキスト/api/userにマッピングされていると仮定すると、その理由は、そのコントローラへのすべての要求が保護されていないため、SecurityContextもないことを意味します。その行を削除して、Spring Securityがその行を保護するようにします。無視する方法のJavadocのから

抜粋:(SecurityContextが含む)春のセキュリティが提供する

Webセキュリティは、HttpServletRequestのその試合には使用できません。

+0

大変感謝しています。 – user3170702

関連する問題