spring - 为什么 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=?");
}
}
解决方案
我假设你指的是这条线,
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
在这种情况下,您不需要这条线,它没有在任何地方使用。根据文档,在更大的答案中,SecurityContextHolder.getContext() 永远不会为空。但是,对 getAuthentication() 的调用将为空,除非有与会话关联的经过身份验证的主体。
推荐阅读
- html - img 标签(在 nav 内)扰乱了它之后所有元素的定位(边距也变得无用)
- python - Pandas Rolling vs Scipy kurtosis - 严重的数值不准确
- python - 为什么我的模型没有对所有数据进行训练(Tensorflow 2)
- c# - 我有一个模态表单 ShowDialog 我想关闭表单 如果 1 按下按钮(有效) 2 如果静态变量中的值发生变化(无效)
- reactjs - 如何在 Redux 中使用扩展运算符获取内部数组和对象的旧状态
- python - TensorFlow 自定义层:获取实际的 Batch Size
- alert - 如何在多/空时只发出一次警报?通用解决方案不起作用
- r - 如何列出和计算 R 中的每个属性?
- python - 正则表达式提取字符串的第一部分
- php - 如何获取由 PHP simplexml_load_string 解析的 XML 元素 (SimpleXMLElement) 的字符串类型内容?