Spring Security中JWT密钥@Value注入失效问题求助
JwtProvider中@Value注入secret为null的解决方案
问题场景
在Spring Boot项目集成JWT与Spring Security时,自定义过滤器CustomAuthorizationFilter调用JwtProvider.verifyJwt()方法时,发现通过@Value("${jwt.secret}")声明的secret字段值为null,但项目中其他组件的@Value注入均正常。
原因分析
问题出在SecurityConfiguration的配置代码中:你通过new JwtProvider(userDetailsService)手动创建了JwtProvider实例,而手动new的对象不在Spring容器的管理范围内,Spring无法对其进行依赖注入(包括@Value的配置注入)。
解决步骤
1. 将JwtProvider声明为Spring管理的Bean
在JwtProvider类上添加@Component或@Service注解,让Spring容器负责创建和管理该类的实例:
@Slf4j @Component @RequiredArgsConstructor public class JwtProvider { private final UserDetailsService userDetailsService; @Value("${jwt.secret}") private String secret; private final String tokenPrefix = "Bearer "; // verifyJwt方法实现保持不变 public User verifyJwt(String token) { // ... 原有代码 } }
2. 修改SecurityConfiguration,注入JwtProvider
删除手动new JwtProvider的代码,改为通过构造函数注入Spring容器管理的JwtProvider实例:
@Configuration @EnableWebSecurity @RequiredArgsConstructor public class SecurityConfiguration extends WebSecurityConfigurerAdapter { private final UserDetailsService userDetailsService; private final BCryptPasswordEncoder bCryptPasswordEncoder; private final JwtProvider jwtProvider; // 注入Spring管理的JwtProvider @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder); } @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .cors() .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() .antMatchers("/contact/**", "/user/duplicate/**", "/user/new/**", "/user/login/**", "/user/auth/**", "/user/findId/**", "/user/findPw/**/**", "/swagger-ui/index.html/**") .permitAll() .antMatchers("/user", "/user/**", "/profile/**") .authenticated() .and() .addFilterBefore(new CustomAuthorizationFilter(jwtProvider), UsernamePasswordAuthenticationFilter.class); } }
3. 确认配置文件存在jwt.secret配置
确保你的application.properties或application.yml中正确配置了密钥:
# application.properties示例 jwt.secret=your-strong-secret-key-here
验证
启动项目后,JwtProvider由Spring容器创建,@Value会正常读取配置文件中的jwt.secret值,调用verifyJwt()方法时不会再出现NullPointerException。
内容的提问来源于stack exchange,提问作者gs97ahn
相关产品推荐
相关产品推荐

