为 JWT 使用过滤器时,HttpServletRequest 为 null,headers 适用于邮递员,但不适用于本地主机
HttpServletRequest is null when using filter for JWT, headers work on postman but not localhost
我正在为 front-end 使用 React,为后端使用 Java spring 启动。在我使用 Bcrypt 对密码进行编码之前,我的 api 一直在工作,但现在似乎在每次响应为空的 api 调用之前内部过滤器都有问题...
这是我的WebSecurityConfig.java
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService myUserDetailsService;
@Autowired
private JwtRequestFilter jwtRequestFilter;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(myUserDetailsService).passwordEncoder(passwordEncode());
}
@Bean
public PasswordEncoder passwordEncode(){
return new BCryptPasswordEncoder();
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf().disable()
.authorizeRequests().antMatchers("/authenticate").permitAll()
.antMatchers("/personInfo").permitAll()
.antMatchers("/signup").permitAll().
anyRequest().authenticated().and().
addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class).exceptionHandling();
}
}
这是我的 JWTRequestFilter.java
我在想这可能与 passwordEncoder() 有关,因为当我不使用 BcryptPasswordEncoder() 时我的电话正在工作...
@Component
public class JwtRequestFilter extends OncePerRequestFilter {
@Autowired
private MyUserDetailsService userDetailsService;
@Autowired
private JwtUtil jwtUtil;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
if(request == null){
System.out.println("request is null");
}
final String authorizationHeader = request.getHeader("Authorization");
String username = null;
String jwt = null;
if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
jwt = authorizationHeader.substring(7);
username = jwtUtil.extractUsername(jwt);
}
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
if (jwtUtil.validateToken(jwt, userDetails)) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
usernamePasswordAuthenticationToken
.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
}
}
chain.doFilter(request, response);
}
}
我正在为 front-end 使用 React 并使用 axios
进行调用
async totals(){
console.log('Bearer ', localStorage.getItem('id_token'));
let data = await axios.get("http://localhost:8080/totals", {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.getItem('id_token')
}
})
.then(this._checkStatus);
return data.request.response;
}
当我在邮递员中使用令牌时,api 工作,所以问题出在初始请求和过滤器之间...
我得到的错误是 -
对“http://localhost:8080/totals' from origin 'http://localhost:3000”处的 XMLHttpRequest 的访问已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP 正常状态。
感谢您的宝贵时间:)
如果有人遇到同样的问题,我通过在 WebSecurityConfig.java
中的 configure(HttpSecurity httpSecurity) 方法末尾添加这一行来解决它
httpSecurity.cors();
:)
我正在为 front-end 使用 React,为后端使用 Java spring 启动。在我使用 Bcrypt 对密码进行编码之前,我的 api 一直在工作,但现在似乎在每次响应为空的 api 调用之前内部过滤器都有问题...
这是我的WebSecurityConfig.java
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService myUserDetailsService;
@Autowired
private JwtRequestFilter jwtRequestFilter;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(myUserDetailsService).passwordEncoder(passwordEncode());
}
@Bean
public PasswordEncoder passwordEncode(){
return new BCryptPasswordEncoder();
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf().disable()
.authorizeRequests().antMatchers("/authenticate").permitAll()
.antMatchers("/personInfo").permitAll()
.antMatchers("/signup").permitAll().
anyRequest().authenticated().and().
addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class).exceptionHandling();
}
}
这是我的 JWTRequestFilter.java
我在想这可能与 passwordEncoder() 有关,因为当我不使用 BcryptPasswordEncoder() 时我的电话正在工作...
@Component
public class JwtRequestFilter extends OncePerRequestFilter {
@Autowired
private MyUserDetailsService userDetailsService;
@Autowired
private JwtUtil jwtUtil;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
if(request == null){
System.out.println("request is null");
}
final String authorizationHeader = request.getHeader("Authorization");
String username = null;
String jwt = null;
if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
jwt = authorizationHeader.substring(7);
username = jwtUtil.extractUsername(jwt);
}
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
if (jwtUtil.validateToken(jwt, userDetails)) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
usernamePasswordAuthenticationToken
.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
}
}
chain.doFilter(request, response);
}
}
我正在为 front-end 使用 React 并使用 axios
进行调用async totals(){
console.log('Bearer ', localStorage.getItem('id_token'));
let data = await axios.get("http://localhost:8080/totals", {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.getItem('id_token')
}
})
.then(this._checkStatus);
return data.request.response;
}
当我在邮递员中使用令牌时,api 工作,所以问题出在初始请求和过滤器之间...
我得到的错误是 - 对“http://localhost:8080/totals' from origin 'http://localhost:3000”处的 XMLHttpRequest 的访问已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP 正常状态。
感谢您的宝贵时间:)
如果有人遇到同样的问题,我通过在 WebSecurityConfig.java
中的 configure(HttpSecurity httpSecurity) 方法末尾添加这一行来解决它httpSecurity.cors();
:)