我正在开发一个简单的REST服务,注册用户可以在其中发布内容。
注册和身份验证工作正常,但是,当我尝试向任何受保护的路径发送POST
或GET
请求时,我在Postman中看到一个200状态代码,但响应正文中没有任何内容。
如果需要,我可以提供完整的源代码,但我认为问题出在过滤器类或配置类的某个地方。
我的配置:
http
.csrf().disable()
.sessionManagement()
.sessionCreationPolicy(STATELESS)
.and()
.addFilterAfter(new JwtFilter(userService, jwtUtils), BasicAuthenticationFilter.class)
.authorizeRequests()
.antMatchers("/api/v1/register/**", "/api/v1/users/authenticate").permitAll()
.anyRequest().authenticated();
我的JwtFilter
类:
@RequiredArgsConstructor
public class JwtFilter extends OncePerRequestFilter {
private final UserService userService;
private final JwtUtils jwtUtils;
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
var header = request.getHeader(HttpHeaders.AUTHORIZATION);
if (header == null || !header.startsWith(jwtUtils.Bearer)) {
chain.doFilter(request, response);
return;
}
var jwt = header.replace(jwtUtils.Bearer, "");
var username = jwtUtils.extractUsername(jwt);
if (username == null && SecurityContextHolder.getContext().getAuthentication() != null) {
chain.doFilter(request, response);
return;
}
var user = userService.loadUserByUsername(username);
if (!jwtUtils.validateToken(jwt, user) || !user.isEnabled()) {
chain.doFilter(request, response);
return;
}
var passwordAuthToken = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
passwordAuthToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); // implies that request should contain user details?
SecurityContextHolder.getContext().setAuthentication(passwordAuthToken);
}
}
1条答案
按热度按时间tag5nh1u1#
正如@dur在评论中提到的,问题是我在
doFilterInternal
函数的末尾遗漏了一行chain.doFilter(request, response);
。现在,它应该如下所示: