Why SecurityContextHolder.getContext() == null?



我不运行我的应用程序,因为身份验证 == 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=?");
}
}

我假设你指的是这一行,

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

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

最新更新