java Spring Security getAuthentication() 返回 null

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36411947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 01:25:11  来源:igfitidea点击:

Spring Security getAuthentication() returns null

javaspringspring-security

提问by user3170702

I'm trying the return the currently logged in user from my Spring Boot + AngularJS application, but SecurityContextHolder.getContext().getAuthentication()returns null.

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

回答by dunni

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.

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

Excerpt from the Javadoc of the ignoring method:

忽略方法的 Javadoc 摘录:

Web Security provided by Spring Security (including the SecurityContext) will not be available on HttpServletRequest that match.

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