我的JwtFilter:
public class JWTAuthorizationFilter extends BasicAuthenticationFilter { public JWTAuthorizationFilter(AuthenticationManager authManager) { super(authManager); } @Override protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException { String header = req.getHeader("Authorization"); if (header == null || !header.startsWith("Bearer ")) { chain.doFilter(req, res); return; } UsernamePasswordAuthenticationToken authentication = getAuthentication(req); SecurityContextHolder.getContext().setAuthentication(authentication); chain.doFilter(req, res); } private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) { String token = request.getHeader("Authorization"); if (token != null) { // parse the token. byte[] keyBytes = Decoders.BASE64.decode("kaslsafdhlkjsdfhlksjdafhlaksjdfhlaskajdhflaksdaf87687687asdafasdhfasdfsdfdfjalskjfhlaskdhflasdjhl3434"); Key key = Keys.hmacShaKeyFor(keyBytes); String cleanToken = token.replace("Bearer ", ""); String user = Jwts.parser().setSigningKey(key).parseClaimsJws(cleanToken).getBody().getSubject(); if (user != null) { return new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>()); } return null; } return null; } }
并抛出“ JWT签名与本地计算的签名不匹配。JWT有效性无法断言并且不应被信任。” 例外。
我试图抓住它authenticationEntryPoint(new JwtAuthenticationEntryPoint()):
@Component("restAuthenticationEntryPoint") public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint { public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException, ServletException { response.setContentType("application/json"); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.getOutputStream().println("{ \"error\": \"" + authenticationException.getMessage() + "\" }"); } }
但是我得到:
{ "error": "Full authentication is required to access this resource" }
如何从过滤器获取异常并传递给http答案?