【问题标题】:Spring Security getAuthentication() returns nullSpring Security getAuthentication() 返回 null
【发布时间】:2016-07-24 13:02:18
【问题描述】:

我正在尝试从我的 Spring Boot + AngularJS 应用程序返回当前登录的用户,但 SecurityContextHolder.getContext().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;
    }
}

控制器:

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

【问题讨论】:

    标签: java spring spring-security


    【解决方案1】:

    假设您显示的控制器映射到上下文/api/user,那么原因是因为您已将web.ignoring().antMatchers("/api/user"); 行添加到您的安全配置中,这意味着对该控制器的所有请求都不受保护,并且因此也没有SecurityContext。删除该行,以便 Spring Security 保护它。

    忽略方法的Javadoc节选:

    Spring Security 提供的 Web Security(包括 SecurityContext)在匹配的 HttpServletRequest 上将不可用。

    【讨论】:

      猜你喜欢
      • 2013-07-08
      • 2021-12-23
      • 2014-04-07
      • 2012-07-02
      • 2013-07-02
      • 2015-08-17
      • 2014-06-15
      • 2019-04-28
      相关资源
      最近更新 更多