SC_UNAUTHORIZED returns Spring 引导中的 403
SC_UNAUTHORIZED returns 403 in Spring Boot
我有以下 JWT 过滤器
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, MalformedJwtException {
final String authorizationHeader = request.getHeader("Authorization");
String username = null;
String jwt = null;
try {
if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
jwt = authorizationHeader.substring(7);
username = jwtUtil.extractUsername(jwt);
}
} catch (MalformedJwtException e) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
...
chain.doFilter(request, response);
}
但出于某种原因,我仍然收到 403 响应而不是 401。
{
"timestamp": "2020-07-08T15:59:50.696+0000",
"status": 403,
"error": "Forbidden",
"message": "Access Denied",
"path": "/ping"
}
知道可能是什么问题吗?我尝试了不同的 returns,但它们都是 500 或 403。
- 由于您是直接处理响应,因此您必须执行类似这样的操作
StringBuilder sb = new StringBuilder();
sb.append("{ ");
sb.append("\"error\": \"Unauthorized\" ");
sb.append("\"message\": \"Unauthorized\"");
sb.append("\"path\": \"")
.append(request.getRequestURL())
.append("\"");
sb.append("} ");
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().write(sb.toString());
return;
我有以下 JWT 过滤器
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, MalformedJwtException {
final String authorizationHeader = request.getHeader("Authorization");
String username = null;
String jwt = null;
try {
if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
jwt = authorizationHeader.substring(7);
username = jwtUtil.extractUsername(jwt);
}
} catch (MalformedJwtException e) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
...
chain.doFilter(request, response);
}
但出于某种原因,我仍然收到 403 响应而不是 401。
{
"timestamp": "2020-07-08T15:59:50.696+0000",
"status": 403,
"error": "Forbidden",
"message": "Access Denied",
"path": "/ping"
}
知道可能是什么问题吗?我尝试了不同的 returns,但它们都是 500 或 403。
- 由于您是直接处理响应,因此您必须执行类似这样的操作
StringBuilder sb = new StringBuilder();
sb.append("{ ");
sb.append("\"error\": \"Unauthorized\" ");
sb.append("\"message\": \"Unauthorized\"");
sb.append("\"path\": \"")
.append(request.getRequestURL())
.append("\"");
sb.append("} ");
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().write(sb.toString());
return;