java - Spring Security getAuthentication() 返回 null

标签 java spring spring-security

我正在尝试从 Spring Boot + AngularJS 应用程序返回当前登录的用户,但是 SecurityContextHolder.getContext().getAuthentication()返回空值。

安全配置:

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

最佳答案

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

忽略方法的 Javadoc 摘录:

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

关于java - Spring Security getAuthentication() 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36411947/

相关文章:

java - 一种节省空间的数据结构,用于存储和查找大量(均匀分布的)整数

java - MP3 文件无法使用 jl 库播放

spring - 有没有办法 @Autowire 需要构造函数参数的 bean?

java - 如何在Spring Security中实现不同类型的用户

java - 如何在 spring security 中仅通过 ip 地址对用户进行身份验证?

java - 从列表到整数。无法转换查询结果

java - Spring 长轮询

java - 使用spring boot使用gmail smtp发送邮件

spring-security - Spring Security OAuth2 - 自定义身份验证

java - 将 Hadoop MapReduce 输出写入 2 个平面文件