首页 > 解决方案 > 为什么 SecurityContextHolder.getContext() == null?

问题描述

我不运行我的应用程序,因为 auth == null。为什么?我使用 spring boot 2.2.7.RELEASE 和 spring-security-oauth2-autoconfigure。

启动 SecurityContextHolder.getContext() 时始终等于 null

@Component
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Autowired
    UserRepository userRepository;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Bean
    public PasswordEncoder encoder() {
        return new BCryptPasswordEncoder();
    }

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/addPet").authenticated()
                .antMatchers("/", "/**").access("permitAll")
                .and().oauth2Login().loginPage("/login").defaultSuccessUrl("/", true).and().logout().logoutSuccessUrl("/")


                .and().formLogin().loginPage("/login").loginProcessingUrl("/login").usernameParameter("login").passwordParameter("password")
                .defaultSuccessUrl("/", true).and().logout().logoutSuccessUrl("/").deleteCookies("JSESSIONID").and().csrf().disable();

    }

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource)
                .usersByUsernameQuery(
                        "select login, password, enabled from users where login=?")
                .authoritiesByUsernameQuery(
                        "select login, role from users where login=?");
    }
}

标签: springspring-securityoauth-2.0

解决方案


我假设你指的是这条线,

Authentication auth = SecurityContextHolder.getContext().getAuthentication();

在这种情况下,您不需要这条线,它没有在任何地方使用。根据文档,在更大的答案中,SecurityContextHolder.getContext() 永远不会为空。但是,对 getAuthentication() 的调用将为空,除非有与会话关联的经过身份验证的主体。


推荐阅读